
'use client';

import { useState, useRef } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult } from '@/lib/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { mockSellers } from '@/lib/data';
import { Upload, FileText, X, CheckCircle, MoreVertical } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { format } from 'date-fns';

type UploadedInvoice = {
    id: string;
    invoiceNumber: string;
    merchantName: string;
    fileName: string;
    uploadDate: string;
};

const mockUploaded: UploadedInvoice[] = [
    { id: 'up-1', invoiceNumber: 'EXT-001', merchantName: 'Chic Boutique', fileName: 'july_invoice.pdf', uploadDate: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString() },
    { id: 'up-2', invoiceNumber: 'EXT-002', merchantName: 'Gadget World', fileName: 'invoice_q2.pdf', uploadDate: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString() },
];

export default function FinanceUploadInvoicePage() {
  
  const handleBookingComplete = (result: BookingResult) => {};

  const [selectedMerchant, setSelectedMerchant] = useState('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploadedInvoices, setUploadedInvoices] = useState<UploadedInvoice[]>(mockUploaded);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { toast } = useToast();

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
        setSelectedFile(e.target.files[0]);
    }
  };

  const handleUpload = () => {
    if (!selectedMerchant || !selectedFile) {
        toast({ variant: 'destructive', title: 'Error', description: 'Please select a merchant and a file to upload.' });
        return;
    }

    const newInvoice: UploadedInvoice = {
        id: `up-${Date.now()}`,
        invoiceNumber: `EXT-${Math.floor(Math.random() * 900) + 100}`,
        merchantName: mockSellers.find(s => s.id === selectedMerchant)?.name || 'Unknown',
        fileName: selectedFile.name,
        uploadDate: new Date().toISOString(),
    };

    setUploadedInvoices(prev => [newInvoice, ...prev]);
    toast({ title: 'Upload Successful', description: `Invoice ${selectedFile.name} has been uploaded for ${newInvoice.merchantName}.` });

    // Reset form
    setSelectedMerchant('');
    setSelectedFile(null);
    if(fileInputRef.current) fileInputRef.current.value = '';
  };

  return (
    <SidebarProvider>
      <DashboardLayout onBookingComplete={handleBookingComplete} userRole="finance">
        <div className="flex flex-col gap-8">
          <Card>
            <CardHeader>
              <CardTitle>Upload Invoice</CardTitle>
              <CardDescription>
                Upload externally generated invoices for merchants.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="grid md:grid-cols-2 gap-4">
                    <div>
                        <label className="text-sm font-medium">Select Merchant</label>
                        <Select value={selectedMerchant} onValueChange={setSelectedMerchant}>
                            <SelectTrigger>
                                <SelectValue placeholder="Select a merchant..." />
                            </SelectTrigger>
                            <SelectContent>
                                {mockSellers.map(seller => (
                                    <SelectItem key={seller.id} value={seller.id}>{seller.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                     <div 
                        className="border-2 border-dashed rounded-lg p-6 text-center cursor-pointer flex flex-col items-center justify-center h-full"
                        onClick={() => fileInputRef.current?.click()}
                    >
                         <input type="file" ref={fileInputRef} onChange={handleFileChange} className="hidden" accept=".pdf,.doc,.docx,.csv" />
                        {selectedFile ? (
                            <div className="flex items-center gap-2 text-green-600">
                                <CheckCircle className="h-5 w-5" />
                                <span>{selectedFile.name}</span>
                                <Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground" onClick={(e) => { e.stopPropagation(); setSelectedFile(null); if(fileInputRef.current) fileInputRef.current.value = '';}}>
                                    <X className="h-4 w-4" />
                                </Button>
                            </div>
                        ) : (
                            <div className="flex items-center gap-2 text-muted-foreground">
                                <Upload className="h-5 w-5" />
                                <span>Click to select or drag & drop file</span>
                            </div>
                        )}
                    </div>
                </div>
            </CardContent>
            <CardFooter>
                 <Button onClick={handleUpload} disabled={!selectedFile || !selectedMerchant}>Upload Invoice</Button>
            </CardFooter>
          </Card>

          <Card>
             <CardHeader>
              <CardTitle>Uploaded Invoices</CardTitle>
              <CardDescription>
                A log of all externally uploaded invoices.
              </CardDescription>
            </CardHeader>
            <CardContent>
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Invoice #</TableHead>
                            <TableHead>Merchant</TableHead>
                            <TableHead>File Name</TableHead>
                            <TableHead>Upload Date</TableHead>
                            <TableHead className="text-right">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {uploadedInvoices.map(invoice => (
                            <TableRow key={invoice.id}>
                                <TableCell className="font-medium text-primary">{invoice.invoiceNumber}</TableCell>
                                <TableCell>{invoice.merchantName}</TableCell>
                                <TableCell>
                                    <div className="flex items-center gap-2">
                                        <FileText className="h-4 w-4 text-muted-foreground"/>
                                        {invoice.fileName}
                                    </div>
                                </TableCell>
                                <TableCell>{format(new Date(invoice.uploadDate), 'dd MMM, yyyy')}</TableCell>
                                <TableCell className="text-right">
                                    <Button variant="ghost" size="icon">
                                        <MoreVertical className="h-4 w-4"/>
                                    </Button>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    </SidebarProvider>
  );
}

