'use client';

import { useState, useEffect } from 'react';
import { SidebarProvider } from '@/components/ui/sidebar';
import { DashboardLayout } from '@/components/dashboard-layout';
import type { BookingResult, Complaint, Parcel } from '@/lib/types';
import { mockComplaints, mockUser, mockParcels } from '@/lib/data';
import { ComplaintsTable } from '@/components/complaints/complaints-table';
import { Button } from '@/components/ui/button';
import { PlusCircle, Search } from 'lucide-react';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { format, differenceInHours } from 'date-fns';

export default function ComplaintsPage() {
  const [complaints, setComplaints] = useState<Complaint[]>([]);
  const [consignmentNumber, setConsignmentNumber] = useState('');
  const [parcel, setParcel] = useState<Parcel | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();


  useEffect(() => {
    // Filter complaints for the logged-in seller
    const sellerComplaints = mockComplaints.filter(c => c.sellerId === mockUser.id);
    setComplaints(sellerComplaints);
  }, []);
  
  const handleBookingComplete = (result: BookingResult) => {
    // This page doesn't create bookings, so this can be empty
  };

  const handleComplaintAdded = (newComplaint: Complaint) => {
    setComplaints(prevComplaints => [newComplaint, ...prevComplaints]);
  };
  
  const handleSearch = () => {
    setIsLoading(true);
    setTimeout(() => {
      const foundParcel = mockParcels.find(p => p.orderReferenceNumber === consignmentNumber || p.id === consignmentNumber);
      if (foundParcel) {
        setParcel(foundParcel);
      } else {
        setParcel(null);
        toast({
          variant: 'destructive',
          title: 'Not Found',
          description: 'No consignment found with this number.',
        });
      }
      setIsLoading(false);
    }, 500);
  };
  
  const handleFileComplaint = () => {
    if (!parcel) return;

    const now = new Date();
    // In a real app, this would be the actual delivery/return date
    const lastUpdateDate = new Date(parcel.bookingDate); 
    const hoursSinceUpdate = differenceInHours(now, lastUpdateDate);
    
    // Check if status is Delivered or Returned
    if (parcel.status !== 'Delivered' && parcel.status !== 'Returned') {
         toast({
            variant: 'destructive',
            title: 'Invalid Status',
            description: 'Complaints can only be filed for Delivered or Returned parcels.',
        });
        return;
    }

    if (hoursSinceUpdate > 24) {
      toast({
        variant: 'destructive',
        title: 'Complaint Window Closed',
        description: 'This consignment is beyond the 24-hour complaint window. Kindly contact your BDM for further assistance.',
      });
    } else {
      // Logic to open complaint form/dialog would go here
      toast({
        title: 'Success',
        description: 'Complaint filed successfully for ' + parcel.id,
      });
    }
  };

  const InfoField = ({ label, value }: { label: string, value: string | number | undefined }) => (
      <div>
        <label className="text-sm font-medium text-muted-foreground">{label}</label>
        <Input readOnly value={value || ''} className="mt-1 bg-muted/50" />
      </div>
  );


  return (
    <SidebarProvider>
        <DashboardLayout onBookingComplete={handleBookingComplete} userRole='seller'>
            <div className="flex flex-col gap-8">
                 <Card>
                    <CardHeader>
                      <div className="flex flex-wrap items-center justify-between gap-4">
                         <CardTitle>Complaint Request</CardTitle>
                         <div className="flex items-center gap-2">
                            <label className="text-sm font-medium">Consignment Note Number</label>
                            <Input 
                                value={consignmentNumber}
                                onChange={(e) => setConsignmentNumber(e.target.value)}
                                placeholder="Enter Consignment Number"
                            />
                            <Button onClick={handleSearch} disabled={isLoading || !consignmentNumber}>
                                <Search className="mr-2 h-4 w-4" />
                                {isLoading ? 'Searching...' : 'Search'}
                            </Button>
                         </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <p className="text-sm font-semibold border-b pb-2">Consignment Information</p>
                        {parcel ? (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-4">
                               {/* Left Column */}
                               <div className="space-y-4">
                                   <InfoField label="Booking Date" value={format(new Date(parcel.bookingDate), 'dd-MMM-yyyy')} />
                                   <InfoField label="Order Reference" value={parcel.orderReferenceNumber} />
                                   <InfoField label="Origin" value={parcel.pickupCity} />
                                   <InfoField label="Consignee Name" value={parcel.recipientName} />
                                   <div>
                                     <label className="text-sm font-medium text-muted-foreground">Consignee Address</label>
                                     <Textarea readOnly value={parcel.address} className="mt-1 bg-muted/50" rows={2}/>
                                   </div>
                                   <InfoField label="Pieces" value={parcel.items} />
                                   <div>
                                     <label className="text-sm font-medium text-muted-foreground">Product Detail</label>
                                     <Textarea readOnly value={parcel.orderDetail} className="mt-1 bg-muted/50" rows={2}/>
                                   </div>
                               </div>
                               {/* Right Column */}
                               <div className="space-y-4">
                                   <InfoField label="Cost Center" value={parcel.sellerId} />
                                   <InfoField label="Service" value={parcel.orderType} />
                                   <InfoField label="Destination" value={parcel.city} />
                                   <InfoField label="Consignee Contact" value={parcel.contact} />
                                   <InfoField label="Weight" value={`${parcel.bookingWeight} kg`} />
                                   <InfoField label="Delivery Status" value={parcel.status} />
                                   <InfoField label="COD Amount" value={`PKR ${parcel.codAmount.toFixed(2)}`} />
                               </div>
                               {/* Full-width bottom field */}
                                <div className="md:col-span-2">
                                    <label className="text-sm font-medium text-muted-foreground">Delivery Status Desc</label>
                                    <Textarea placeholder="Add complaint details here..." className="mt-1" rows={3}/>
                               </div>
                            </div>
                        ) : (
                             <div className="flex items-center justify-center h-64 border-2 border-dashed rounded-lg bg-muted/50">
                                <p className="text-muted-foreground">Search for a consignment to view its details.</p>
                            </div>
                        )}
                    </CardContent>
                    {parcel && (
                         <CardFooter className="border-t pt-6">
                            <Button onClick={handleFileComplaint}>File Complaint</Button>
                        </CardFooter>
                    )}
                  </Card>
                <ComplaintsTable complaints={complaints} />
            </div>
        </DashboardLayout>
    </SidebarProvider>
  );
}
