'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 { documentsApi, usersApi, residencesApi, tasksApi } from '@/lib/api';
import type { UpdateDocumentRequest } 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';

const DOCUMENT_TYPES = [
  { value: 'general', label: 'General' },
  { value: 'warranty', label: 'Warranty' },
  { value: 'receipt', label: 'Receipt' },
  { value: 'contract', label: 'Contract' },
  { value: 'insurance', label: 'Insurance' },
  { value: 'manual', label: 'Manual' },
];

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

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

  const { data: document, isLoading: documentLoading } = useQuery({
    queryKey: ['document', documentId],
    queryFn: () => documentsApi.get(documentId),
    enabled: !!documentId,
  });

  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: tasksData } = useQuery({
    queryKey: ['tasks', { per_page: 1000 }],
    queryFn: () => tasksApi.list({ per_page: 1000 }),
  });

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

  useEffect(() => {
    if (document && !formInitialized) {
      setFormData({
        residence_id: document.residence_id,
        created_by_id: document.created_by_id,
        title: document.title,
        description: document.description,
        document_type: document.document_type,
        file_url: document.file_url,
        file_name: document.file_name,
        file_size: document.file_size,
        mime_type: document.mime_type,
        purchase_date: document.purchase_date,
        expiry_date: document.expiry_date,
        purchase_price: document.purchase_price,
        vendor: document.vendor,
        serial_number: document.serial_number,
        model_number: document.model_number,
        provider: document.provider,
        provider_contact: document.provider_contact,
        claim_phone: document.claim_phone,
        claim_email: document.claim_email,
        claim_website: document.claim_website,
        notes: document.notes,
        task_id: document.task_id,
        is_active: document.is_active,
      });
      setFormInitialized(true);
    }
  }, [document, formInitialized]);

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

  const updateMutation = useMutation({
    mutationFn: (data: UpdateDocumentRequest) => documentsApi.update(documentId, data),
    onSuccess: () => {
      toast.success('Document updated successfully');
      router.push(`/documents/${documentId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update document');
    },
  });

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

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

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Assignment</CardTitle>
            <CardDescription>Document 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>
            <div className="space-y-2">
              <Label htmlFor="task_id">Related Task</Label>
              <Select
                value={formData.task_id?.toString() || 'none'}
                onValueChange={(value) => updateField('task_id', value === 'none' ? undefined : Number(value))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select task" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">None</SelectItem>
                  {tasksData?.data?.map((task) => (
                    <SelectItem key={task.id} value={task.id.toString()}>
                      {task.title} (#{task.id})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Document details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="title">Title *</Label>
                <Input
                  id="title"
                  value={formData.title || ''}
                  onChange={(e) => updateField('title', e.target.value)}
                  placeholder="Document title"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="document_type">Document Type</Label>
                <Select
                  value={formData.document_type || ''}
                  onValueChange={(value) => updateField('document_type', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select type" />
                  </SelectTrigger>
                  <SelectContent>
                    {DOCUMENT_TYPES.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </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="Document description..."
                rows={3}
              />
            </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={2}
              />
            </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>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>File Information</CardTitle>
            <CardDescription>File details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="file_url">File URL</Label>
                <Input
                  id="file_url"
                  value={formData.file_url || ''}
                  onChange={(e) => updateField('file_url', e.target.value)}
                  placeholder="https://..."
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="file_name">File Name</Label>
                <Input
                  id="file_name"
                  value={formData.file_name || ''}
                  onChange={(e) => updateField('file_name', e.target.value)}
                  placeholder="document.pdf"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="file_size">File Size (bytes)</Label>
                <Input
                  id="file_size"
                  type="number"
                  value={formData.file_size ?? ''}
                  onChange={(e) => updateField('file_size', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="0"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="mime_type">MIME Type</Label>
                <Input
                  id="mime_type"
                  value={formData.mime_type || ''}
                  onChange={(e) => updateField('mime_type', e.target.value)}
                  placeholder="application/pdf"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Purchase Information</CardTitle>
            <CardDescription>Purchase and warranty details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-3 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 || undefined)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="expiry_date">Expiry Date</Label>
                <Input
                  id="expiry_date"
                  type="date"
                  value={formData.expiry_date || ''}
                  onChange={(e) => updateField('expiry_date', e.target.value || undefined)}
                />
              </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="0.00"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Product Details</CardTitle>
            <CardDescription>Vendor and product information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="vendor">Vendor</Label>
              <Input
                id="vendor"
                value={formData.vendor || ''}
                onChange={(e) => updateField('vendor', e.target.value)}
                placeholder="Vendor name"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="serial_number">Serial Number</Label>
                <Input
                  id="serial_number"
                  value={formData.serial_number || ''}
                  onChange={(e) => updateField('serial_number', e.target.value)}
                  placeholder="Serial number"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="model_number">Model Number</Label>
                <Input
                  id="model_number"
                  value={formData.model_number || ''}
                  onChange={(e) => updateField('model_number', e.target.value)}
                  placeholder="Model number"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Provider/Warranty Contact</CardTitle>
            <CardDescription>Contact information for claims or support</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="provider">Provider</Label>
                <Input
                  id="provider"
                  value={formData.provider || ''}
                  onChange={(e) => updateField('provider', e.target.value)}
                  placeholder="Provider name"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="provider_contact">Provider Contact</Label>
                <Input
                  id="provider_contact"
                  value={formData.provider_contact || ''}
                  onChange={(e) => updateField('provider_contact', e.target.value)}
                  placeholder="Contact name"
                />
              </div>
            </div>
            <div className="grid grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="claim_phone">Claim Phone</Label>
                <Input
                  id="claim_phone"
                  value={formData.claim_phone || ''}
                  onChange={(e) => updateField('claim_phone', e.target.value)}
                  placeholder="1-800-555-0123"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="claim_email">Claim Email</Label>
                <Input
                  id="claim_email"
                  type="email"
                  value={formData.claim_email || ''}
                  onChange={(e) => updateField('claim_email', e.target.value)}
                  placeholder="claims@example.com"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="claim_website">Claim Website</Label>
                <Input
                  id="claim_website"
                  value={formData.claim_website || ''}
                  onChange={(e) => updateField('claim_website', e.target.value)}
                  placeholder="https://claims.example.com"
                />
              </div>
            </div>
          </CardContent>
        </Card>

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