import React, { useEffect } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  useProperty,
  useCreateProperty,
  useUpdateProperty,
  useLandlordContacts,
} from '@/hooks/useProperties';

const propertySchema = z.object({
  property_class: z.string().optional(),
  business_category: z.string().optional(),
  reference: z.string().optional(),
  display_address: z.string().min(1, 'Display address is required'),
  address_line_1: z.string().optional(),
  address_line_2: z.string().optional(),
  town_city: z.string().optional(),
  county: z.string().optional(),
  postcode: z.string().optional(),
  country: z.string().optional(),
  is_overseas: z.boolean().optional(),
  headline: z.string().optional(),
  summary: z.string().optional(),
  full_description: z.string().optional(),
  branch: z.string().optional(),
  lead_staff: z.string().optional(),
  price: z.coerce.number().optional().nullable(),
  price_qualifier: z.string().optional(),
  valuation_price: z.coerce.number().optional().nullable(),
  minimum_acceptable_price: z.coerce.number().optional().nullable(),
  on_the_market: z.boolean().optional(),
  marketing_tag: z.string().optional(),
  virtual_tour_link: z.string().optional(),
  virtual_tour_link_2: z.string().optional(),
  link_on_website: z.string().optional(),
  rightmove_link: z.string().optional(),
  zoopla_link: z.string().optional(),
  on_the_market_link: z.string().optional(),
  epc_rating: z.string().optional(),
  epc_band: z.string().optional(),
  additional_information: z.string().optional(),
  dashboard_note: z.string().optional(),
  viewing_arrangements: z.string().optional(),
  ground_rent: z.coerce.number().optional().nullable(),
  maintenance_charge: z.coerce.number().optional().nullable(),
  exclude_from_all_portals: z.boolean().optional(),
  exclude_from_website: z.boolean().optional(),
  exclude_from_window_rotator: z.boolean().optional(),
  feature_on_homepage: z.boolean().optional(),
  local_authority: z.string().optional(),
  additional_field_1: z.string().optional(),
  additional_field_2: z.string().optional(),
  property_type: z.string().optional(),
  number_of_bedrooms: z.coerce.number().optional().nullable(),
  number_of_receptions: z.coerce.number().optional().nullable(),
  number_of_bathrooms: z.coerce.number().optional().nullable(),
  council_tax_band: z.string().optional(),
  landlord_id: z.string().optional().nullable(),
  status: z.string().optional(),
  date_available: z.string().optional(),
  deposit: z.coerce.number().optional().nullable(),
  letting_service: z.string().optional(),
  letting_fee: z.coerce.number().optional().nullable(),
  management_fee: z.coerce.number().optional().nullable(),
  landlord_payment_frequency: z.string().optional(),
  has_gas: z.boolean().optional(),
  gas_certificate_expiry: z.string().optional(),
  pat_test_expiry: z.string().optional(),
  electricity_certificate_expiry: z.string().optional(),
  epc_expiry: z.string().optional(),
  insurance_expiry: z.string().optional(),
  legionella_risk_assessment_date: z.string().optional(),
  smoke_co_alarm_expiry: z.string().optional(),
  property_licence_expiry: z.string().optional(),
  property_licence_type: z.string().optional(),
  property_licence_notes: z.string().optional(),
});

type PropertyFormData = z.infer<typeof propertySchema>;

interface PropertyFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  propertyId?: string;
}

export function PropertyFormDialog({ open, onOpenChange, propertyId }: PropertyFormDialogProps) {
  const { data: property, isLoading: propertyLoading } = useProperty(propertyId);
  const { data: landlordData, isLoading: landlordsLoading } = useLandlordContacts();
  const createProperty = useCreateProperty();
  const updateProperty = useUpdateProperty();

  const form = useForm<PropertyFormData>({
    resolver: zodResolver(propertySchema),
    defaultValues: {
      display_address: '',
      country: 'United Kingdom',
      is_overseas: false,
      on_the_market: false,
      exclude_from_all_portals: false,
      exclude_from_website: false,
      exclude_from_window_rotator: false,
      feature_on_homepage: false,
      has_gas: false,
      status: 'available',
    },
  });

  useEffect(() => {
    if (property) {
      form.reset({
        ...property,
        price: property.price ?? undefined,
        valuation_price: property.valuation_price ?? undefined,
        minimum_acceptable_price: property.minimum_acceptable_price ?? undefined,
        ground_rent: property.ground_rent ?? undefined,
        maintenance_charge: property.maintenance_charge ?? undefined,
        deposit: property.deposit ?? undefined,
        letting_fee: property.letting_fee ?? undefined,
        management_fee: property.management_fee ?? undefined,
        number_of_bedrooms: property.number_of_bedrooms ?? undefined,
        number_of_receptions: property.number_of_receptions ?? undefined,
        number_of_bathrooms: property.number_of_bathrooms ?? undefined,
      });
    } else {
      form.reset({
        display_address: '',
        country: 'United Kingdom',
        is_overseas: false,
        on_the_market: false,
        exclude_from_all_portals: false,
        exclude_from_website: false,
        exclude_from_window_rotator: false,
        feature_on_homepage: false,
        has_gas: false,
        status: 'available',
      });
    }
  }, [property, form]);

  const onSubmit = async (data: PropertyFormData) => {
    const propertyData = {
      ...data,
      landlord_id: data.landlord_id || null,
    };

    if (propertyId) {
      await updateProperty.mutateAsync({ id: propertyId, ...propertyData });
    } else {
      await createProperty.mutateAsync(propertyData);
    }
    onOpenChange(false);
  };

  const isLoading = createProperty.isPending || updateProperty.isPending;
  const hasLandlords = landlordData?.contacts && landlordData.contacts.length > 0;
  const landlordTagExists = landlordData?.hasLandlordTag;

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

        {!landlordsLoading && !landlordTagExists && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Landlord Tag Missing</AlertTitle>
            <AlertDescription>
              No "Landlord" tag exists in the system. Please create a "Landlord" tag first and assign it to contacts who are landlords.
            </AlertDescription>
          </Alert>
        )}

        {!landlordsLoading && landlordTagExists && !hasLandlords && (
          <Alert>
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>No Landlords Found</AlertTitle>
            <AlertDescription>
              No contacts with the "Landlord" tag were found. Please add the "Landlord" tag to relevant contacts first.
            </AlertDescription>
          </Alert>
        )}

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <ScrollArea className="h-[60vh] pr-4">
              <Tabs defaultValue="basic" className="w-full">
                <TabsList className="grid grid-cols-5 w-full mb-4">
                  <TabsTrigger value="basic">Basic</TabsTrigger>
                  <TabsTrigger value="address">Address</TabsTrigger>
                  <TabsTrigger value="description">Description</TabsTrigger>
                  <TabsTrigger value="financial">Financial</TabsTrigger>
                  <TabsTrigger value="compliance">Compliance</TabsTrigger>
                </TabsList>

                <TabsContent value="basic" className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="reference"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Reference</FormLabel>
                          <FormControl>
                            <Input {...field} placeholder="Property reference" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="property_class"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Property Class</FormLabel>
                          <FormControl>
                            <Input {...field} placeholder="e.g., Residential" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="business_category"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Business Category</FormLabel>
                          <FormControl>
                            <Input {...field} placeholder="e.g., Lettings" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="property_type"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Property Type</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || ''}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select type" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="flat">Flat</SelectItem>
                              <SelectItem value="house">House</SelectItem>
                              <SelectItem value="bungalow">Bungalow</SelectItem>
                              <SelectItem value="maisonette">Maisonette</SelectItem>
                              <SelectItem value="studio">Studio</SelectItem>
                              <SelectItem value="room">Room</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="number_of_bedrooms"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Bedrooms</FormLabel>
                          <FormControl>
                            <Input type="number" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="number_of_bathrooms"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Bathrooms</FormLabel>
                          <FormControl>
                            <Input type="number" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="number_of_receptions"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Receptions</FormLabel>
                          <FormControl>
                            <Input type="number" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="status"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Status</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || 'available'}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select status" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="available">Available</SelectItem>
                              <SelectItem value="let">Let</SelectItem>
                              <SelectItem value="under_offer">Under Offer</SelectItem>
                              <SelectItem value="sold">Sold</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="landlord_id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Landlord</FormLabel>
                          <Select 
                            onValueChange={field.onChange} 
                            value={field.value || ''}
                            disabled={!hasLandlords}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={hasLandlords ? "Select landlord" : "No landlords available"} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {landlordData?.contacts.map((contact) => (
                                <SelectItem key={contact.id} value={contact.id}>
                                  {contact.first_name} {contact.last_name} - {contact.email}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="date_available"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Date Available</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <div className="flex flex-wrap gap-6">
                    <FormField
                      control={form.control}
                      name="on_the_market"
                      render={({ field }) => (
                        <FormItem className="flex items-center gap-2">
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                          <FormLabel className="!mt-0">On the Market</FormLabel>
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="feature_on_homepage"
                      render={({ field }) => (
                        <FormItem className="flex items-center gap-2">
                          <FormControl>
                            <Switch checked={field.value} onCheckedChange={field.onChange} />
                          </FormControl>
                          <FormLabel className="!mt-0">Feature on Homepage</FormLabel>
                        </FormItem>
                      )}
                    />
                  </div>
                </TabsContent>

                <TabsContent value="address" className="space-y-4">
                  <FormField
                    control={form.control}
                    name="display_address"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Display Address *</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="Address shown publicly" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="address_line_1"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Address Line 1</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="address_line_2"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Address Line 2</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="town_city"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Town/City</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="county"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>County</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="postcode"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Postcode</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="country"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Country</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="local_authority"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Local Authority</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="council_tax_band"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Council Tax Band</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || ''}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select band" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].map((band) => (
                                <SelectItem key={band} value={band}>{band}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <FormField
                    control={form.control}
                    name="is_overseas"
                    render={({ field }) => (
                      <FormItem className="flex items-center gap-2">
                        <FormControl>
                          <Switch checked={field.value} onCheckedChange={field.onChange} />
                        </FormControl>
                        <FormLabel className="!mt-0">Is Overseas Property</FormLabel>
                      </FormItem>
                    )}
                  />
                </TabsContent>

                <TabsContent value="description" className="space-y-4">
                  <FormField
                    control={form.control}
                    name="headline"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Headline</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="Property headline" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="summary"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Summary</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={3} placeholder="Brief summary" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="full_description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Full Description</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={6} placeholder="Detailed property description" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="viewing_arrangements"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Viewing Arrangements</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={2} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="additional_information"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Additional Information</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={2} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="dashboard_note"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Dashboard Note</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={2} placeholder="Internal notes" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="virtual_tour_link"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Virtual Tour Link</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="virtual_tour_link_2"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Virtual Tour Link 2</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="link_on_website"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Website Link</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="rightmove_link"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Rightmove Link</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="zoopla_link"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Zoopla Link</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="on_the_market_link"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>OnTheMarket Link</FormLabel>
                          <FormControl>
                            <Input {...field} type="url" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </TabsContent>

                <TabsContent value="financial" className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="price"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Price (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="price_qualifier"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Price Qualifier</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || ''}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select qualifier" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="price_on_application">Price on Application</SelectItem>
                              <SelectItem value="guide_price">Guide Price</SelectItem>
                              <SelectItem value="offers_over">Offers Over</SelectItem>
                              <SelectItem value="offers_invited">Offers Invited</SelectItem>
                              <SelectItem value="fixed_price">Fixed Price</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="valuation_price"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Valuation Price (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="minimum_acceptable_price"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Minimum Acceptable Price (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="deposit"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Deposit (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="ground_rent"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Ground Rent (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="maintenance_charge"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Maintenance Charge (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <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="managed">Managed</SelectItem>
                              <SelectItem value="rent_collect">Rent Collect</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="letting_fee"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Letting Fee (£)</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" {...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" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="landlord_payment_frequency"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Landlord Payment Frequency</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || ''}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select frequency" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="monthly">Monthly</SelectItem>
                              <SelectItem value="quarterly">Quarterly</SelectItem>
                              <SelectItem value="annually">Annually</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </TabsContent>

                <TabsContent value="compliance" className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="epc_rating"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>EPC Rating</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="epc_band"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>EPC Band</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value || ''}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select band" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {['A', 'B', 'C', 'D', 'E', 'F', 'G'].map((band) => (
                                <SelectItem key={band} value={band}>{band}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="epc_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>EPC Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="gas_certificate_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Gas Certificate Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="pat_test_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>PAT Test Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="electricity_certificate_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Electricity Certificate Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="insurance_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Insurance Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="legionella_risk_assessment_date"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Legionella Risk Assessment</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="smoke_co_alarm_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Smoke & CO Alarm Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="property_licence_expiry"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Property Licence Expiry</FormLabel>
                          <FormControl>
                            <Input type="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="property_licence_type"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Property Licence Type</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <FormField
                    control={form.control}
                    name="property_licence_notes"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Property Licence Notes</FormLabel>
                        <FormControl>
                          <Textarea {...field} rows={2} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="has_gas"
                    render={({ field }) => (
                      <FormItem className="flex items-center gap-2">
                        <FormControl>
                          <Switch checked={field.value} onCheckedChange={field.onChange} />
                        </FormControl>
                        <FormLabel className="!mt-0">Has Gas</FormLabel>
                      </FormItem>
                    )}
                  />
                  <div className="border-t pt-4 mt-4">
                    <h4 className="font-medium mb-4">Portal Settings</h4>
                    <div className="flex flex-wrap gap-6">
                      <FormField
                        control={form.control}
                        name="exclude_from_all_portals"
                        render={({ field }) => (
                          <FormItem className="flex items-center gap-2">
                            <FormControl>
                              <Switch checked={field.value} onCheckedChange={field.onChange} />
                            </FormControl>
                            <FormLabel className="!mt-0">Exclude from All Portals</FormLabel>
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="exclude_from_website"
                        render={({ field }) => (
                          <FormItem className="flex items-center gap-2">
                            <FormControl>
                              <Switch checked={field.value} onCheckedChange={field.onChange} />
                            </FormControl>
                            <FormLabel className="!mt-0">Exclude from Website</FormLabel>
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="exclude_from_window_rotator"
                        render={({ field }) => (
                          <FormItem className="flex items-center gap-2">
                            <FormControl>
                              <Switch checked={field.value} onCheckedChange={field.onChange} />
                            </FormControl>
                            <FormLabel className="!mt-0">Exclude from Window Rotator</FormLabel>
                          </FormItem>
                        )}
                      />
                    </div>
                  </div>
                </TabsContent>
              </Tabs>
            </ScrollArea>

            <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading ? 'Saving...' : propertyId ? 'Update Property' : 'Create Property'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
