import React, { useEffect, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { useSupabaseEmployeeData } from "@/hooks/useSupabaseEmployeeData";
import { useToast } from "@/hooks/use-toast";
import { Currency } from "@/lib/currency";
import { useAuth } from "@/hooks/useAuth";

interface AdminDataEntryModalProps {
  isOpen: boolean;
  onClose: () => void;
  onDataUpdate: () => void;
}

export const AdminDataEntryModal = ({ isOpen, onClose, onDataUpdate }: AdminDataEntryModalProps) => {
  const { employees, addTransaction } = useSupabaseEmployeeData();
  const { user } = useAuth();
  const { toast } = useToast();

  const isEmployee = user?.role === 'employee';
  const lockedEmployeeId = isEmployee
    ? employees.find(e => e.emp_id === user?.empId || e.email === user?.email)?.id
    : undefined;

  const [selectedEmployeeId, setSelectedEmployeeId] = useState<string>('');
  const [collectionAmount, setCollectionAmount] = useState<string>('');
  const [depositAmount, setDepositAmount] = useState<string>('');
  const [currency, setCurrency] = useState<Currency>('USD');
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isEmployee && lockedEmployeeId) {
      setSelectedEmployeeId(lockedEmployeeId);
    }
  }, [isEmployee, lockedEmployeeId, isOpen]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedEmployeeId) {
      toast({
        title: "Error",
        description: "Please select an employee",
        variant: "destructive"
      });
      return;
    }

    const collection = parseFloat(collectionAmount) || 0;
    const deposit = parseFloat(depositAmount) || 0;

    if (collection === 0 && deposit === 0) {
      toast({
        title: "Error",
        description: "Please enter at least one amount (collection or deposit)",
        variant: "destructive"
      });
      return;
    }

    setLoading(true);

    try {
      await addTransaction(selectedEmployeeId, {
        transaction_date: format(selectedDate, 'yyyy-MM-dd'),
        collection_amount: collection,
        deposit_amount: deposit,
        currency,
      });

      toast({
        title: "Success",
        description: "Transaction added successfully",
      });

      // Reset form
      setSelectedEmployeeId('');
      setCollectionAmount('');
      setDepositAmount('');
      setCurrency('USD');
      setSelectedDate(new Date());
      
      onDataUpdate();
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to add transaction. Please try again.",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setSelectedEmployeeId('');
    setCollectionAmount('');
    setDepositAmount('');
    setCurrency('USD');
    setSelectedDate(new Date());
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px] bg-white">
        <DialogHeader>
          <DialogTitle className="text-2xl font-bold text-slate-800">
            {isEmployee ? "Submit Transaction" : "Insert Employee Data"}
          </DialogTitle>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-6 mt-6">
          <div className="space-y-2">
            <Label htmlFor="employee" className="text-sm font-medium text-slate-700">
              {isEmployee ? "Employee" : "Select Employee"}
            </Label>
            <Select
              value={selectedEmployeeId}
              onValueChange={setSelectedEmployeeId}
              disabled={isEmployee}
            >
              <SelectTrigger>
                <SelectValue placeholder={isEmployee ? "Your account" : "Choose an employee"} />
              </SelectTrigger>
              <SelectContent>
                {(isEmployee && lockedEmployeeId
                  ? employees.filter(e => e.id === lockedEmployeeId)
                  : employees
                ).map(employee => (
                  <SelectItem key={employee.id} value={employee.id}>
                    {employee.name} (ID: {employee.emp_id})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {isEmployee && !lockedEmployeeId && (
              <p className="text-xs text-red-600">
                Your account is not linked to an employee record. Ask an admin to set your Employee ID.
              </p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="date" className="text-sm font-medium text-slate-700">
              Transaction Date
            </Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  className={cn(
                    "w-full justify-start text-left font-normal",
                    !selectedDate && "text-muted-foreground"
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {selectedDate ? format(selectedDate, "PPP") : <span>Pick a date</span>}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={selectedDate}
                  onSelect={(date) => date && setSelectedDate(date)}
                  initialFocus
                  className="pointer-events-auto"
                />
              </PopoverContent>
            </Popover>
          </div>

          <div className="space-y-2">
            <Label className="text-sm font-medium text-slate-700">Currency</Label>
            <Select value={currency} onValueChange={(v) => setCurrency(v as Currency)}>
              <SelectTrigger>
                <SelectValue placeholder="Select currency" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="USD">US Dollar (USD)</SelectItem>
                <SelectItem value="LBP">Lebanese Pound (LBP)</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="collection" className="text-sm font-medium text-slate-700">
                MM Collection Amount ({currency})
              </Label>
              <Input
                id="collection"
                type="number"
                placeholder="0.00"
                value={collectionAmount}
                onChange={(e) => setCollectionAmount(e.target.value)}
                className="text-right"
                step={currency === 'USD' ? '0.01' : '1'}
                min="0"
                disabled={loading}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="deposit" className="text-sm font-medium text-slate-700">
                Deposit Amount ({currency})
              </Label>
              <Input
                id="deposit"
                type="number"
                placeholder="0.00"
                value={depositAmount}
                onChange={(e) => setDepositAmount(e.target.value)}
                className="text-right"
                step={currency === 'USD' ? '0.01' : '1'}
                min="0"
                disabled={loading}
              />
            </div>
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <Button type="button" variant="outline" onClick={handleClose} disabled={loading}>
              Cancel
            </Button>
            <Button type="submit" className="bg-blue-600 hover:bg-blue-700" disabled={loading}>
              {loading ? "Adding..." : "Add Transaction"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
