import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { AlertCircle } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  useCreateTenancy,
  useUpdateTenancy,
  useTenantContacts,
  useProperties,
  TenancyWithRelations,
} from '@/hooks/useTenancies';

const formSchema = z.object({
  reference: z.string().optional(),
  property_id: z.string().optional(),
  tenant_id: z.string().optional(),
  start_date: z.string().optional(),
  end_date: z.string().optional(),
  rent: z.coerce.number().optional(),
  rent_payment_frequency: z.string().optional(),
  deposit: z.coerce.number().optional(),
  where_deposit_held: z.string().optional(),
  letting_service: z.string().optional(),
  status: z.string().optional(),
  letting_fee: z.coerce.number().optional(),
  management_fee: z.coerce.number().optional(),
  is_periodic: z.boolean().optional(),
  rent_review_date: z.string().optional(),
  branch: z.string().optional(),
  is_rent_guaranteed: z.boolean().optional(),
  tenancy_agreement_special_clause: z.string().optional(),
  renewal: z.string().optional(),
  is_hmo: z.boolean().optional(),
  break_clause: z.string().optional(),
  notice_period: z.string().optional(),
  lead_staff: z.string().optional(),
});

type FormData = z.infer<typeof formSchema>;

interface TenancyFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tenancy?: TenancyWithRelations | null;
}

export function TenancyFormDialog({ open, onOpenChange, tenancy }: TenancyFormDialogProps) {
  const createTenancy = useCreateTenancy();
  const updateTenancy = useUpdateTenancy();
  const { data: tenantData } = useTenantContacts();
  const { data: properties } = useProperties();

  const [activeTab, setActiveTab] = useState('basic');

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      reference: '',
      property_id: '',
      tenant_id: '',
      start_date: '',
      end_date: '',
      rent: undefined,
      rent_payment_frequency: '',
      deposit: undefined,
      where_deposit_held: '',
      letting_service: '',
      status: 'active',
      letting_fee: undefined,
      management_fee: undefined,
      is_periodic: false,
      rent_review_date: '',
      branch: '',
      is_rent_guaranteed: false,
      tenancy_agreement_special_clause: '',
      renewal: '',
      is_hmo: false,
      break_clause: '',
      notice_period: '',
      lead_staff: '',
    },
  });

  useEffect(() => {
    if (tenancy) {
      form.reset({
        reference: tenancy.reference || '',
        property_id: tenancy.property_id || '',
        tenant_id: tenancy.tenant_id || '',
        start_date: tenancy.start_date || '',
        end_date: tenancy.end_date || '',
        rent: tenancy.rent ?? undefined,
        rent_payment_frequency: tenancy.rent_payment_frequency || '',
        deposit: tenancy.deposit ?? undefined,
        where_deposit_held: tenancy.where_deposit_held || '',
        letting_service: tenancy.letting_service || '',
        status: tenancy.status || 'active',
        letting_fee: tenancy.letting_fee ?? undefined,
        management_fee: tenancy.management_fee ?? undefined,
        is_periodic: tenancy.is_periodic || false,
        rent_review_date: tenancy.rent_review_date || '',
        branch: tenancy.branch || '',
        is_rent_guaranteed: tenancy.is_rent_guaranteed || false,
        tenancy_agreement_special_clause: tenancy.tenancy_agreement_special_clause || '',
        renewal: tenancy.renewal || '',
        is_hmo: tenancy.is_hmo || false,
        break_clause: tenancy.break_clause || '',
        notice_period: tenancy.notice_period || '',
        lead_staff: tenancy.lead_staff || '',
      });
    } else {
      form.reset();
    }
    setActiveTab('basic');
  }, [tenancy, form, open]);

  const onSubmit = async (data: FormData) => {
    const cleanData = {
      ...data,
      property_id: data.property_id || null,
      tenant_id: data.tenant_id || null,
      start_date: data.start_date || null,
      end_date: data.end_date || null,
      rent: data.rent || null,
      deposit: data.deposit || null,
      letting_fee: data.letting_fee || null,
      management_fee: data.management_fee || null,
      rent_review_date: data.rent_review_date || null,
    };

    if (tenancy) {
      await updateTenancy.mutateAsync({ id: tenancy.id, ...cleanData });
    } else {
      await createTenancy.mutateAsync(cleanData);
    }
    onOpenChange(false);
  };

  const showNoTenantTagAlert = tenantData && !tenantData.hasTenantTag;
  const showNoTenantContactsAlert = tenantData?.hasTenantTag && tenantData.contacts.length === 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh]">
        <DialogHeader>
          <DialogTitle>{tenancy ? 'Edit Tenancy' : 'Add Tenancy'}</DialogTitle>
        </DialogHeader>

        {showNoTenantTagAlert && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>No Tenant Tag Found</AlertTitle>
            <AlertDescription>
              Please create a "Tenant" tag in Settings → Tags before adding tenants.
            </AlertDescription>
          </Alert>
        )}

        {showNoTenantContactsAlert && (
          <Alert>
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>No Tenant Contacts</AlertTitle>
            <AlertDescription>
              No contacts with the "Tenant" tag found. Add the Tenant tag to contacts to select
              them as tenants.
            </AlertDescription>
          </Alert>
        )}

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="basic">Basic</TabsTrigger>
                <TabsTrigger value="financial">Financial</TabsTrigger>
                <TabsTrigger value="terms">Terms</TabsTrigger>
                <TabsTrigger value="other">Other</TabsTrigger>
              </TabsList>

              <ScrollArea className="h-[400px] pr-4">
                {/* Basic Tab */}
                <TabsContent value="basic" className="space-y-4 mt-4">
                  <FormField
                    control={form.control}
                    name="reference"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Reference</FormLabel>
                        <FormControl>
                          <Input placeholder="TEN-001" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="property_id"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Property</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select a property" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {properties?.map((property) => (
                              <SelectItem key={property.id} value={property.id}>
                                {property.display_address ||
                                  property.address_line_1 ||
                                  property.reference ||
                                  'Unnamed Property'}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="tenant_id"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Tenant</FormLabel>
                        <Select
                          onValueChange={field.onChange}
                          value={field.value}
                          disabled={!tenantData?.hasTenantTag || tenantData.contacts.length === 0}
                        >
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select a tenant" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {tenantData?.contacts.map((contact) => (
                              <SelectItem key={contact.id} value={contact.id}>
                                {contact.first_name} {contact.last_name} - {contact.email}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="start_date"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Start Date</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="end_date"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>End Date</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={form.control}
                    name="status"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Status</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select status" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="active">Active</SelectItem>
                            <SelectItem value="pending">Pending</SelectItem>
                            <SelectItem value="ended">Ended</SelectItem>
                            <SelectItem value="cancelled">Cancelled</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="is_periodic"
                      render={({ field }) => (
                        <FormItem className="flex items-center justify-between rounded-lg border p-3">
                          <FormLabel className="cursor-pointer">Is Periodic</FormLabel>
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="is_hmo"
                      render={({ field }) => (
                        <FormItem className="flex items-center justify-between rounded-lg border p-3">
                          <FormLabel className="cursor-pointer">Is HMO</FormLabel>
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  </div>
                </TabsContent>

                {/* Financial Tab */}
                <TabsContent value="financial" className="space-y-4 mt-4">
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="rent"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Rent (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" placeholder="0.00" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="rent_payment_frequency"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Payment Frequency</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select frequency" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="weekly">Weekly</SelectItem>
                              <SelectItem value="fortnightly">Fortnightly</SelectItem>
                              <SelectItem value="monthly">Monthly</SelectItem>
                              <SelectItem value="quarterly">Quarterly</SelectItem>
                              <SelectItem value="annually">Annually</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="deposit"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Deposit (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" placeholder="0.00" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="where_deposit_held"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Where Deposit Held</FormLabel>
                          <FormControl>
                            <Input placeholder="e.g., DPS, TDS" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={form.control}
                    name="letting_service"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Letting Service</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select service" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="let_only">Let Only</SelectItem>
                            <SelectItem value="rent_collection">Rent Collection</SelectItem>
                            <SelectItem value="fully_managed">Fully Managed</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="letting_fee"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Letting Fee (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" placeholder="0.00" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="management_fee"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Management Fee (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" placeholder="0.00" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  <FormField
                    control={form.control}
                    name="is_rent_guaranteed"
                    render={({ field }) => (
                      <FormItem className="flex items-center justify-between rounded-lg border p-3">
                        <FormLabel className="cursor-pointer">Is Rent Guaranteed</FormLabel>
                        <FormControl>
                          <Switch checked={field.value} onCheckedChange={field.onChange} />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="rent_review_date"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Rent Review Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </TabsContent>

                {/* Terms Tab */}
                <TabsContent value="terms" className="space-y-4 mt-4">
                  <FormField
                    control={form.control}
                    name="renewal"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Renewal</FormLabel>
                        <FormControl>
                          <Input placeholder="e.g., 12 months renewal" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="break_clause"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Break Clause</FormLabel>
                        <FormControl>
                          <Input placeholder="e.g., 6 month break clause" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="notice_period"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Notice Period</FormLabel>
                        <FormControl>
                          <Input placeholder="e.g., 2 months" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="tenancy_agreement_special_clause"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Special Clause</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="Enter any special clauses..."
                            className="min-h-[100px]"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </TabsContent>

                {/* Other Tab */}
                <TabsContent value="other" className="space-y-4 mt-4">
                  <FormField
                    control={form.control}
                    name="branch"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Branch</FormLabel>
                        <FormControl>
                          <Input placeholder="Branch name" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="lead_staff"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Lead Staff</FormLabel>
                        <FormControl>
                          <Input placeholder="Staff member name" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </TabsContent>
              </ScrollArea>
            </Tabs>

            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={createTenancy.isPending || updateTenancy.isPending}
              >
                {createTenancy.isPending || updateTenancy.isPending
                  ? 'Saving...'
                  : tenancy
                  ? 'Update Tenancy'
                  : 'Create Tenancy'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
