import {useState} from 'react';
import {Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle} from '@/components/ui/dialog';
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {useAppDispatch, useAppSelector, addTransaction} from '@/store';

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export default function AddTransactionDialog({open, onOpenChange}: Props) {
  const dispatch = useAppDispatch();
  const {categories} = useAppSelector(state => state.cashflow);
  const [form, setForm] = useState({type: 'expense' as 'income' | 'expense', name: '', amount: '', category: '', date: new Date().toISOString().split('T')[0]});

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    dispatch(
      addTransaction({
        id: crypto.randomUUID(),
        type: form.type,
        name: form.name,
        amount: parseFloat(form.amount) || 0,
        category: form.category,
        date: form.date
      })
    );
    onOpenChange(false);
    setForm({type: 'expense', name: '', amount: '', category: '', date: new Date().toISOString().split('T')[0]});
  };

  const categoryList = form.type === 'income' ? categories.income : categories.expense;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="card-elevated sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Add Transaction</DialogTitle>
          <DialogDescription>Record a one-time transaction</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label>Type</Label>
              <Select value={form.type} onValueChange={v => setForm({...form, type: v as 'income' | 'expense', category: ''})}>
                <SelectTrigger className="input-depth">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="income">Income</SelectItem>
                  <SelectItem value="expense">Expense</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="name">Description</Label>
              <Input
                id="name"
                placeholder="e.g., Groceries"
                value={form.name}
                onChange={e => setForm({...form, name: e.target.value})}
                className="input-depth"
                required
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="amount">Amount</Label>
                <Input
                  id="amount"
                  type="number"
                  step="0.01"
                  min="0"
                  placeholder="0.00"
                  value={form.amount}
                  onChange={e => setForm({...form, amount: e.target.value})}
                  className="input-depth"
                  required
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="date">Date</Label>
                <Input id="date" type="date" value={form.date} onChange={e => setForm({...form, date: e.target.value})} className="input-depth" required />
              </div>
            </div>
            <div className="grid gap-2">
              <Label>Category</Label>
              <Select value={form.category} onValueChange={v => setForm({...form, category: v})} required>
                <SelectTrigger className="input-depth">
                  <SelectValue placeholder="Select category" />
                </SelectTrigger>
                <SelectContent>
                  {categoryList.map(c => (
                    <SelectItem key={c} value={c}>
                      {c}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={!form.name || !form.amount || !form.category}>
              Add Transaction
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
