import { useState } from "react";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Loader2 } from "lucide-react";
import AccountDropdown from "@/components/AccountDropdown";

interface TransactionFormData {
  transaction_date: string;
  description: string;
  amount: string;
  type: string;
  chart_of_account_id: string | null;
}

interface TransactionFormDialogProps {
  isOpen: boolean;
  onClose: (open: boolean) => void;
  onSubmit: (data: TransactionFormData) => void;
  loading?: boolean;
  title?: string;
  showChartOfAccount?: boolean;
}

export default function TransactionFormDialog({
  isOpen,
  onClose,
  onSubmit,
  loading = false,
  title = "Add Transaction",
  showChartOfAccount = false,
}: TransactionFormDialogProps) {
  const [formData, setFormData] = useState({
    transaction_date: new Date().toISOString().split("T")[0],
    description: "",
    amount: "",
    type: "debit",
    chart_of_account_id: "",
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit({
      ...formData,
      chart_of_account_id: formData.chart_of_account_id || null,
    });
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>Enter the details for this manual transaction.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Date</Label>
            <Input type="date" name="transaction_date" required value={formData.transaction_date} onChange={handleChange} />
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Input name="description" required placeholder="Description or Memo" value={formData.description} onChange={handleChange} />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Amount</Label>
              <Input type="number" step="0.01" min="0.01" name="amount" required placeholder="0.00" value={formData.amount} onChange={handleChange} />
            </div>
            <div className="space-y-2">
              <Label>Type</Label>
              <Select value={formData.type} onValueChange={(val) => setFormData((prev) => ({ ...prev, type: val }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="debit">Debit</SelectItem>
                  <SelectItem value="credit">Credit</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {showChartOfAccount && (
            <div className="space-y-2">
              <Label>Chart of Account</Label>
              <AccountDropdown
                value={formData.chart_of_account_id}
                onChange={(val) => setFormData((prev) => ({ ...prev, chart_of_account_id: val }))}
                placeholder="Optional – select account"
              />
            </div>
          )}

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onClose(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save Transaction
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
