import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } 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, SelectGroup, SelectLabel as SLabel } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { Lock } from 'lucide-react';

const schema = z.object({
  association_id: z.string().min(1, 'Association is required'),
  status: z.string().min(1, 'Status is required'),
  amount_owed: z.coerce.number().min(0, 'Total must be positive'), 
  last_notice_date: z.string().optional().nullable(),
  notes: z.string().optional().nullable(),
});

const normalizeCollectionStatus = (status) => status === 'resolved' ? 'closed' : status;

export default function CollectionFinancialDialog({ open, onOpenChange, collection, onSuccess, associations }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const db = supabase;
  
  const { register, handleSubmit, reset, setValue, watch, formState: { errors, isSubmitting, isValid } } = useForm({
    resolver: zodResolver(schema),
    mode: 'onChange',
    defaultValues: {
      amount_owed: 0,
      status: 'open',
    }
  });

  useEffect(() => {
    if (open) {
        if (collection) {
            reset({
                association_id: collection.association_id,
                status: collection.status || 'open',
                amount_owed: collection.amount_owed || 0,
                last_notice_date: collection.last_notice_date || '',
                notes: collection.notes || '',
            });
        } else {
            reset({
                association_id: '',
                status: 'open',
                amount_owed: 0,
                last_notice_date: '',
                notes: '',
            });
        }
    }
  }, [collection, reset, open]);

  const handleSave = async (data) => {
    try {
      const payload = {
        ...data,
        status: normalizeCollectionStatus(data.status),
        last_notice_date: data.last_notice_date || null,
      };

      let error;

      if (collection?.id) {
        const { error: updateError } = await db
          .from('collections')
          .update(payload)
          .eq('id', collection.id);
        error = updateError;
      } else {
        const { error: insertError } = await db
          .from('collections')
          .insert([payload]);
        error = insertError;
      }

      if (error) throw error;

      toast({
        title: "Success",
        description: "Collection financial information updated successfully",
      });
      
      if (onSuccess) onSuccess();
      onOpenChange(false);

    } catch (error) {
      console.error("Submission error:", error);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: error.message || "Failed to save record",
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{collection ? 'Financial Record' : 'Add Financial Record'}</DialogTitle>
          <DialogDescription>
            Update the financial breakdown and status for this collection case.
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(handleSave)} className="space-y-4 py-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="association_id">Association <span className="text-red-500">*</span></Label>
              <Select 
                onValueChange={(val) => setValue('association_id', val)} 
                defaultValue={collection?.association_id}
                disabled={!!collection} 
              >
                <SelectTrigger id="association_id" className={errors.association_id ? "border-red-500" : ""}>
                  <SelectValue placeholder="Select Association" />
                </SelectTrigger>
                <SelectContent>
                  {associations?.map(a => (
                    <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.association_id && <p className="text-red-500 text-xs">{errors.association_id.message}</p>}
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">Status <span className="text-red-500">*</span></Label>
              <Select 
                onValueChange={(val) => setValue('status', val)} 
                defaultValue={collection?.status || 'open'}
              >
                <SelectTrigger id="status" className={errors.status ? "border-red-500" : ""}>
                  <SelectValue placeholder="Select Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="open">Open</SelectItem>
                  <SelectItem value="in_progress">In Progress</SelectItem>
                  <SelectItem value="resolved">Resolved</SelectItem>
                  <SelectItem value="closed">Closed</SelectItem>
                </SelectContent>
              </Select>
              {errors.status && <p className="text-red-500 text-xs">{errors.status.message}</p>}
            </div>

            <div className="space-y-2">
              <Label htmlFor="amount_owed">Amount Owed ($) <span className="text-red-500">*</span></Label>
              <Input 
                id="amount_owed" 
                type="number" 
                step="0.01" 
                min="0"
                {...register('amount_owed')} 
                className={errors.amount_owed ? "border-red-500" : ""}
              />
              {errors.amount_owed && <p className="text-red-500 text-xs">{errors.amount_owed.message}</p>}
            </div>

            <div className="space-y-2">
              <Label htmlFor="last_notice_date">Last Notice Date</Label>
              <Input 
                id="last_notice_date" 
                type="date" 
                {...register('last_notice_date')} 
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="notes">Notes</Label>
            <textarea
              id="notes"
              {...register('notes')}
              rows={3}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent"
            />
          </div>

          <DialogFooter className="mt-6">
            <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting || !isValid}>
              {isSubmitting ? 'Saving...' : (collection ? 'Update Record' : 'Create Record')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}