'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 { contractorsApi, usersApi, residencesApi, lookupsApi } from '@/lib/api';
import type { UpdateContractorRequest } from '@/types/models';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
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 EditContractorPage() {
  const router = useRouter();
  const params = useParams();
  const contractorId = Number(params.id);

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

  const { data: contractor, isLoading: contractorLoading } = useQuery({
    queryKey: ['contractor', contractorId],
    queryFn: () => contractorsApi.get(contractorId),
    enabled: !!contractorId,
  });

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

  const { data: residencesData, isLoading: residencesLoading } = useQuery({
    queryKey: ['residences', { per_page: 1000 }],
    queryFn: () => residencesApi.list({ per_page: 1000 }),
  });

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

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

  useEffect(() => {
    if (contractor && !formInitialized) {
      setFormData({
        residence_id: contractor.residence_id,
        created_by_id: contractor.created_by_id,
        name: contractor.name,
        company: contractor.company,
        phone: contractor.phone,
        email: contractor.email,
        website: contractor.website,
        notes: contractor.notes,
        street_address: contractor.street_address,
        city: contractor.city,
        state_province: contractor.state_province,
        postal_code: contractor.postal_code,
        rating: contractor.rating,
        is_favorite: contractor.is_favorite,
        is_active: contractor.is_active,
        specialty_ids: contractor.specialty_ids,
      });
      setFormInitialized(true);
    }
  }, [contractor, formInitialized]);

  const isDataLoading = contractorLoading || usersLoading || residencesLoading || !formInitialized;

  const updateMutation = useMutation({
    mutationFn: (data: UpdateContractorRequest) => contractorsApi.update(contractorId, data),
    onSuccess: () => {
      toast.success('Contractor updated successfully');
      router.push(`/contractors/${contractorId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update contractor');
    },
  });

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

  const updateField = (field: keyof UpdateContractorRequest, 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={`/contractors/${contractorId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Contractor</h1>
          <p className="text-muted-foreground">Update contractor details</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Assignment</CardTitle>
            <CardDescription>Contractor ownership</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="residence_id">Residence *</Label>
                <Select
                  value={formData.residence_id?.toString() || ''}
                  onValueChange={(value) => updateField('residence_id', Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select residence" />
                  </SelectTrigger>
                  <SelectContent>
                    {residencesData?.data?.map((res) => (
                      <SelectItem key={res.id} value={res.id.toString()}>
                        {res.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="created_by_id">Created By *</Label>
                <Select
                  value={formData.created_by_id?.toString() || ''}
                  onValueChange={(value) => updateField('created_by_id', Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select creator" />
                  </SelectTrigger>
                  <SelectContent>
                    {usersData?.data?.map((user) => (
                      <SelectItem key={user.id} value={user.id.toString()}>
                        {user.username} ({user.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Contractor contact 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="Contractor name"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="company">Company</Label>
                <Input
                  id="company"
                  value={formData.company || ''}
                  onChange={(e) => updateField('company', e.target.value)}
                  placeholder="Company name"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="phone">Phone</Label>
                <Input
                  id="phone"
                  value={formData.phone || ''}
                  onChange={(e) => updateField('phone', e.target.value)}
                  placeholder="555-123-4567"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email || ''}
                  onChange={(e) => updateField('email', e.target.value)}
                  placeholder="contractor@example.com"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="website">Website</Label>
              <Input
                id="website"
                value={formData.website || ''}
                onChange={(e) => updateField('website', e.target.value)}
                placeholder="https://example.com"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                value={formData.notes || ''}
                onChange={(e) => updateField('notes', e.target.value)}
                placeholder="Additional notes..."
                rows={3}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Address</CardTitle>
            <CardDescription>Contractor location</CardDescription>
          </CardHeader>
          <CardContent className="space-y-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="grid grid-cols-3 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 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>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Rating & Specialties</CardTitle>
            <CardDescription>Contractor expertise</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="rating">Rating (0-5)</Label>
              <Input
                id="rating"
                type="number"
                min="0"
                max="5"
                step="0.1"
                value={formData.rating ?? ''}
                onChange={(e) => updateField('rating', e.target.value ? Number(e.target.value) : undefined)}
                placeholder="4.5"
                className="w-32"
              />
            </div>
            <div className="space-y-2">
              <Label>Specialties</Label>
              <div className="grid grid-cols-3 gap-2">
                {specialties?.map((spec: { id: number; name: string }) => (
                  <label key={spec.id} className="flex items-center space-x-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.specialty_ids?.includes(spec.id) || false}
                      onChange={(e) => {
                        const current = formData.specialty_ids || [];
                        if (e.target.checked) {
                          updateField('specialty_ids', [...current, spec.id]);
                        } else {
                          updateField('specialty_ids', current.filter(id => id !== spec.id));
                        }
                      }}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm">{spec.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Status</CardTitle>
            <CardDescription>Contractor status flags</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-6">
              <div className="flex items-center space-x-2">
                <Switch
                  id="is_favorite"
                  checked={formData.is_favorite}
                  onCheckedChange={(checked) => updateField('is_favorite', checked)}
                />
                <Label htmlFor="is_favorite">Favorite</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>

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