import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { Loader2, Repeat } from 'lucide-react';
import { notifyTaskAssignment } from '@/lib/taskNotificationHelper';

export default function TaskDialog({ open, onOpenChange, task, onSuccess, associations = [], users = [] }) {
  const { toast } = useToast();
  const { user } = useAuth();

  const defaultFormData = {
    title: '', description: '', status: 'pending', priority: 'medium',
    association_id: '', assigned_to: 'unassigned', due_date: '',
    client_specific: false, recurring: false, recurring_interval: 'weekly',
    recurring_next_date: '',
  };

  const [formData, setFormData] = useState(defaultFormData);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open) {
      if (task) {
        setFormData({
          title: task.title || '', description: task.description || '',
          status: task.status || 'pending', priority: task.priority || 'medium',
          association_id: task.association_id || task.client_id || '',
          assigned_to: task.assigned_to || 'unassigned',
          due_date: task.due_date ? task.due_date.split('T')[0] : '',
          client_specific: task.client_specific || false,
          recurring: task.recurring || false,
          recurring_interval: task.recurring_interval || 'weekly',
          recurring_next_date: task.recurring_next_date ? task.recurring_next_date.split('T')[0] : '',
        });
      } else {
        setFormData(defaultFormData);
      }
    }
  }, [task, open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (!formData.title.trim()) throw new Error('Task title is required');

      const getUuid = (val) => (!val || val === '' || val === 'unassigned') ? null : val;

      const dataToSubmit = {
        title: formData.title, description: formData.description,
        status: formData.status, priority: formData.priority,
        client_specific: formData.client_specific,
        recurring: formData.recurring,
        association_id: getUuid(formData.association_id),
        client_id: getUuid(formData.association_id),
        assigned_to: getUuid(formData.assigned_to),
        due_date: formData.due_date || null,
        recurring_interval: formData.recurring ? formData.recurring_interval : null,
        recurring_next_date: (formData.recurring && formData.recurring_next_date) ? formData.recurring_next_date : null,
        updated_at: new Date().toISOString()
      };

      if (!task) {
        dataToSubmit.created_by = user.id;
      }

      const { error } = task
        ? await supabase.from('tasks').update(dataToSubmit).eq('id', task.id)
        : await supabase.from('tasks').insert([dataToSubmit]);

      if (error) throw error;

      if (dataToSubmit.assigned_to && (!task || task.assigned_to !== dataToSubmit.assigned_to)) {
        if (dataToSubmit.assigned_to !== user.id) {
          const { data: profile } = await supabase.from('profiles').select('full_name').eq('user_id', user.id).single();
          notifyTaskAssignment(dataToSubmit.title, dataToSubmit.assigned_to, profile?.full_name || user.email);
        }
      }

      toast({ title: task ? 'Task Updated' : 'Task Created', description: `Task has been successfully ${task ? 'updated' : 'created'}.` });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (error) {
      toast({ variant: 'destructive', title: 'Error', description: error.message });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{task ? 'Edit Task' : 'Create New Task'}</DialogTitle>
          <DialogDescription>Manage task details, assignment and status.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="grid gap-4">
            <div className="space-y-2">
              <Label htmlFor="title">Title *</Label>
              <Input id="title" placeholder="Task title" value={formData.title} onChange={e => setFormData({ ...formData, title: e.target.value })} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea id="description" placeholder="Enter task details..." value={formData.description} onChange={e => setFormData({ ...formData, description: e.target.value })} rows={3} />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Status</Label>
                <Select value={formData.status} onValueChange={(val) => setFormData({ ...formData, status: val })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="in-progress">In Progress</SelectItem>
                    <SelectItem value="completed">Completed</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Priority</Label>
                <Select value={formData.priority} onValueChange={(val) => setFormData({ ...formData, priority: val })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="low">Low</SelectItem>
                    <SelectItem value="medium">Medium</SelectItem>
                    <SelectItem value="high">High</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Client</Label>
                <Select value={formData.association_id || ''} onValueChange={(val) => setFormData({ ...formData, association_id: val })}>
                  <SelectTrigger><SelectValue placeholder="Select client" /></SelectTrigger>
                  <SelectContent>
                    {associations.map(a => (<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Assigned To</Label>
                <Select value={formData.assigned_to} onValueChange={(val) => setFormData({ ...formData, assigned_to: val })}>
                  <SelectTrigger><SelectValue placeholder="Unassigned" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="unassigned">Unassigned</SelectItem>
                    {users.map(u => (<SelectItem key={u.id} value={u.id}>{u.name}</SelectItem>))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
              <div className="space-y-2">
                <Label>Due Date</Label>
                <Input type="date" value={formData.due_date} onChange={e => setFormData({ ...formData, due_date: e.target.value })} />
              </div>
              <div className="flex items-center space-x-2 pb-2 h-[42px]">
                <Checkbox id="client_specific" checked={formData.client_specific} onCheckedChange={(checked) => setFormData({ ...formData, client_specific: checked })} />
                <Label htmlFor="client_specific" className="font-normal cursor-pointer">Client Specific Task</Label>
              </div>
            </div>

            <div className="bg-muted/50 p-4 rounded-lg border space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Repeat className="w-4 h-4 text-muted-foreground" />
                  <Label htmlFor="recurring" className="font-semibold">Recurring Task</Label>
                </div>
                <Switch id="recurring" checked={formData.recurring} onCheckedChange={(checked) => setFormData({ ...formData, recurring: checked })} />
              </div>
              {formData.recurring && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 animate-in fade-in slide-in-from-top-2">
                  <div className="space-y-2">
                    <Label className="text-xs uppercase text-muted-foreground">Frequency</Label>
                    <Select value={formData.recurring_interval} onValueChange={(val) => setFormData({ ...formData, recurring_interval: val })}>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="daily">Daily</SelectItem>
                        <SelectItem value="weekly">Weekly</SelectItem>
                        <SelectItem value="monthly">Monthly</SelectItem>
                        <SelectItem value="yearly">Yearly</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs uppercase text-muted-foreground">End Date (Optional)</Label>
                    <Input type="date" value={formData.recurring_next_date} onChange={e => setFormData({ ...formData, recurring_next_date: e.target.value })} />
                  </div>
                </div>
              )}
            </div>
          </div>
          <DialogFooter className="pt-4">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>
              {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              {task ? 'Save Changes' : 'Create Task'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
