'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';

import { residencesApi, usersApi, lookupsApi } from '@/lib/api';
import type { UpdateResidenceRequest } from '@/types/models';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';

export default function EditResidencePage() {
  const router = useRouter();
  const params = useParams();
  const residenceId = Number(params.id);

  const [formData, setFormData] = useState<UpdateResidenceRequest>({});

  const { data: residence, isLoading: residenceLoading } = useQuery({
    queryKey: ['residence', residenceId],
    queryFn: () => residencesApi.get(residenceId),
    enabled: !!residenceId,
  });

  const { data: usersData, isLoading: usersLoading, error: usersError } = useQuery({
    queryKey: ['users', { per_page: 1000 }],
    queryFn: () => usersApi.list({ per_page: 1000 }),
  });

  const { data: residenceTypes } = useQuery({
    queryKey: ['lookups', 'residence-types'],
    queryFn: () => lookupsApi.residenceTypes.list(),
  });

  const [formInitialized, setFormInitialized] = useState(false);

  useEffect(() => {
    if (residence && !formInitialized) {
      setFormData({
        owner_id: residence.owner_id,
        name: residence.name,
        property_type_id: residence.property_type_id,
        street_address: residence.street_address,
        apartment_unit: residence.apartment_unit,
        city: residence.city,
        state_province: residence.state_province,
        postal_code: residence.postal_code,
        country: residence.country,
        bedrooms: residence.bedrooms,
        bathrooms: residence.bathrooms,
        square_footage: residence.square_footage,
        lot_size: residence.lot_size,
        year_built: residence.year_built,
        description: residence.description,
        purchase_date: residence.purchase_date,
        purchase_price: residence.purchase_price,
        is_primary: residence.is_primary,
        is_active: residence.is_active,
      });
      setFormInitialized(true);
    }
  }, [residence, formInitialized]);

  const isDataLoading = residenceLoading || usersLoading || !formInitialized;

  const updateMutation = useMutation({
    mutationFn: (data: UpdateResidenceRequest) => residencesApi.update(residenceId, data),
    onSuccess: () => {
      toast.success('Residence updated successfully');
      router.push(`/residences/${residenceId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update residence');
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name) {
      toast.error('Please enter a residence name');
      return;
    }
    updateMutation.mutate(formData);
  };

  const updateField = (field: keyof UpdateResidenceRequest, value: unknown) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  if (isDataLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href={`/residences/${residenceId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Residence</h1>
          <p className="text-muted-foreground">Update property details</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Ownership</CardTitle>
            <CardDescription>Property ownership details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="owner_id">Owner *</Label>
              <Select
                value={formData.owner_id?.toString() || ''}
                onValueChange={(value) => updateField('owner_id', Number(value))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select owner" />
                </SelectTrigger>
                <SelectContent>
                  {usersData?.data?.map((user) => (
                    <SelectItem key={user.id} value={user.id.toString()}>
                      {user.username} ({user.email})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Update the property details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">Name *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => updateField('name', e.target.value)}
                  placeholder="My Home"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="property_type_id">Property Type</Label>
                <Select
                  value={formData.property_type_id?.toString() || ''}
                  onValueChange={(value) => updateField('property_type_id', value ? Number(value) : undefined)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select type" />
                  </SelectTrigger>
                  <SelectContent>
                    {residenceTypes?.map((type: { id: number; name: string }) => (
                      <SelectItem key={type.id} value={type.id.toString()}>
                        {type.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={formData.description || ''}
                onChange={(e) => updateField('description', e.target.value)}
                placeholder="Property description..."
                rows={3}
              />
            </div>
            <div className="flex items-center gap-6">
              <div className="flex items-center space-x-2">
                <Switch
                  id="is_primary"
                  checked={formData.is_primary}
                  onCheckedChange={(checked) => updateField('is_primary', checked)}
                />
                <Label htmlFor="is_primary">Primary Residence</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="is_active"
                  checked={formData.is_active}
                  onCheckedChange={(checked) => updateField('is_active', checked)}
                />
                <Label htmlFor="is_active">Active</Label>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Address</CardTitle>
            <CardDescription>Property location details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="street_address">Street Address</Label>
                <Input
                  id="street_address"
                  value={formData.street_address || ''}
                  onChange={(e) => updateField('street_address', e.target.value)}
                  placeholder="123 Main St"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="apartment_unit">Apartment/Unit</Label>
                <Input
                  id="apartment_unit"
                  value={formData.apartment_unit || ''}
                  onChange={(e) => updateField('apartment_unit', e.target.value)}
                  placeholder="Apt 4B"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="city">City</Label>
                <Input
                  id="city"
                  value={formData.city || ''}
                  onChange={(e) => updateField('city', e.target.value)}
                  placeholder="City"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="state_province">State/Province</Label>
                <Input
                  id="state_province"
                  value={formData.state_province || ''}
                  onChange={(e) => updateField('state_province', e.target.value)}
                  placeholder="State"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="postal_code">Postal Code</Label>
                <Input
                  id="postal_code"
                  value={formData.postal_code || ''}
                  onChange={(e) => updateField('postal_code', e.target.value)}
                  placeholder="12345"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="country">Country</Label>
                <Input
                  id="country"
                  value={formData.country || ''}
                  onChange={(e) => updateField('country', e.target.value)}
                  placeholder="USA"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Property Details</CardTitle>
            <CardDescription>Physical property characteristics</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label htmlFor="bedrooms">Bedrooms</Label>
                <Input
                  id="bedrooms"
                  type="number"
                  value={formData.bedrooms ?? ''}
                  onChange={(e) => updateField('bedrooms', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="3"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="bathrooms">Bathrooms</Label>
                <Input
                  id="bathrooms"
                  type="number"
                  step="0.5"
                  value={formData.bathrooms ?? ''}
                  onChange={(e) => updateField('bathrooms', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="2.5"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="square_footage">Square Footage</Label>
                <Input
                  id="square_footage"
                  type="number"
                  value={formData.square_footage ?? ''}
                  onChange={(e) => updateField('square_footage', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="2000"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lot_size">Lot Size (acres)</Label>
                <Input
                  id="lot_size"
                  type="number"
                  step="0.01"
                  value={formData.lot_size ?? ''}
                  onChange={(e) => updateField('lot_size', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="0.25"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="year_built">Year Built</Label>
              <Input
                id="year_built"
                type="number"
                value={formData.year_built ?? ''}
                onChange={(e) => updateField('year_built', e.target.value ? Number(e.target.value) : undefined)}
                placeholder="1990"
                className="w-32"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Purchase Information</CardTitle>
            <CardDescription>Property purchase details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="purchase_date">Purchase Date</Label>
                <Input
                  id="purchase_date"
                  type="date"
                  value={formData.purchase_date || ''}
                  onChange={(e) => updateField('purchase_date', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="purchase_price">Purchase Price ($)</Label>
                <Input
                  id="purchase_price"
                  type="number"
                  step="0.01"
                  value={formData.purchase_price ?? ''}
                  onChange={(e) => updateField('purchase_price', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="250000"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4">
          <Button type="button" variant="outline" asChild>
            <Link href={`/residences/${residenceId}`}>Cancel</Link>
          </Button>
          <Button type="submit" disabled={updateMutation.isPending}>
            {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
          </Button>
        </div>
      </form>
    </div>
  );
}
