'use client';

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

import { contractorsApi, usersApi, residencesApi } from '@/lib/api';
import type { CreateContractorRequest } 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 NewContractorPage() {
  const router = useRouter();
  const [formData, setFormData] = useState<CreateContractorRequest>({
    residence_id: 0,
    created_by_id: 0,
    name: '',
    company: '',
    phone: '',
    email: '',
    website: '',
    notes: '',
    city: '',
    state_province: '',
    is_favorite: false,
  });

  const { data: residencesData } = useQuery({
    queryKey: ['residences-list'],
    queryFn: () => residencesApi.list({ per_page: 100, is_active: true }),
  });

  const { data: usersData } = useQuery({
    queryKey: ['users-list'],
    queryFn: () => usersApi.list({ per_page: 100, is_active: true }),
  });

  const createMutation = useMutation({
    mutationFn: (data: CreateContractorRequest) => contractorsApi.create(data),
    onSuccess: () => {
      toast.success('Contractor created successfully');
      router.push('/contractors');
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to create contractor');
    },
  });

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

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

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href="/contractors">
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">New Contractor</h1>
          <p className="text-muted-foreground">Add a new service provider</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Enter the contractor details</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', parseInt(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select residence" />
                  </SelectTrigger>
                  <SelectContent>
                    {residencesData?.data?.map((residence) => (
                      <SelectItem key={residence.id} value={residence.id.toString()}>
                        {residence.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', parseInt(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>
            <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="John Doe"
                />
              </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="ABC Plumbing"
                />
              </div>
            </div>
            <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">Mark as Favorite</Label>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Contact Information</CardTitle>
            <CardDescription>Contact details for this contractor</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <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="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>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Notes</CardTitle>
            <CardDescription>Additional information</CardDescription>
          </CardHeader>
          <CardContent>
            <Textarea
              id="notes"
              value={formData.notes || ''}
              onChange={(e) => updateField('notes', e.target.value)}
              placeholder="Any additional notes about this contractor..."
            />
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4">
          <Button type="button" variant="outline" asChild>
            <Link href="/contractors">Cancel</Link>
          </Button>
          <Button type="submit" disabled={createMutation.isPending}>
            {createMutation.isPending ? 'Creating...' : 'Create Contractor'}
          </Button>
        </div>
      </form>
    </div>
  );
}
