import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Edit, Trash2, Home, User, PoundSterling, Calendar, FileText, Shield, Receipt } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useTenancy, useDeleteTenancy, TenancyWithRelations } from '@/hooks/useTenancies';
import { TenancyFormDialog } from '@/components/tenancies/TenancyFormDialog';
import { TenancyDocumentsTab } from '@/components/tenancies/TenancyDocumentsTab';
import { RentPaymentsTab } from '@/components/tenancies/RentPaymentsTab';
import { format } from 'date-fns';
import { useState } from 'react';

export default function TenancyDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { data: tenancy, isLoading } = useTenancy(id);
  const deleteTenancy = useDeleteTenancy();

  const [formOpen, setFormOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <p>Loading tenancy details...</p>
      </div>
    );
  }

  if (!tenancy) {
    return (
      <div className="flex flex-col items-center justify-center h-64 gap-4">
        <p>Tenancy not found</p>
        <Button onClick={() => navigate('/tenancies')}>Back to Tenancies</Button>
      </div>
    );
  }

  const getStatusColor = (status: string | null) => {
    switch (status) {
      case 'active':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'ended':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
      case 'cancelled':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      default:
        return 'bg-muted text-muted-foreground';
    }
  };

  const formatDate = (date: string | null) => {
    if (!date) return '-';
    return format(new Date(date), 'dd/MM/yyyy');
  };

  const formatCurrency = (amount: number | null) => {
    if (amount === null || amount === undefined) return '-';
    return `£${amount.toLocaleString()}`;
  };

  const handleDelete = async () => {
    await deleteTenancy.mutateAsync(tenancy.id);
    navigate('/tenancies');
  };

  // Get landlord info from property
  const landlord = (tenancy as any).property?.landlord;

  return (
    <div className="space-y-6 p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => navigate('/tenancies')}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold">
                {tenancy.reference || 'Tenancy Details'}
              </h1>
              <Badge className={getStatusColor(tenancy.status)} variant="secondary">
                {tenancy.status || 'Unknown'}
              </Badge>
            </div>
            <p className="text-muted-foreground">
              {(tenancy as any).property?.display_address || (tenancy as any).property?.address_line_1 || 'No property assigned'}
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => setFormOpen(true)}>
            <Edit className="mr-2 h-4 w-4" />
            Edit
          </Button>
          <Button variant="destructive" onClick={() => setDeleteDialogOpen(true)}>
            <Trash2 className="mr-2 h-4 w-4" />
            Delete
          </Button>
        </div>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="details" className="space-y-4">
        <TabsList className="grid w-full grid-cols-7 lg:w-auto lg:grid-cols-none lg:flex">
          <TabsTrigger value="details" className="flex items-center gap-2">
            <Home className="h-4 w-4" />
            <span className="hidden sm:inline">Details</span>
          </TabsTrigger>
          <TabsTrigger value="tenant" className="flex items-center gap-2">
            <User className="h-4 w-4" />
            <span className="hidden sm:inline">Tenant</span>
          </TabsTrigger>
          <TabsTrigger value="financial" className="flex items-center gap-2">
            <PoundSterling className="h-4 w-4" />
            <span className="hidden sm:inline">Financial</span>
          </TabsTrigger>
          <TabsTrigger value="rent" className="flex items-center gap-2">
            <Receipt className="h-4 w-4" />
            <span className="hidden sm:inline">Rent</span>
          </TabsTrigger>
          <TabsTrigger value="documents" className="flex items-center gap-2">
            <FileText className="h-4 w-4" />
            <span className="hidden sm:inline">Documents</span>
          </TabsTrigger>
          <TabsTrigger value="terms" className="flex items-center gap-2">
            <Calendar className="h-4 w-4" />
            <span className="hidden sm:inline">Terms</span>
          </TabsTrigger>
          <TabsTrigger value="landlord" className="flex items-center gap-2">
            <Shield className="h-4 w-4" />
            <span className="hidden sm:inline">Landlord</span>
          </TabsTrigger>
        </TabsList>

        {/* Details Tab */}
        <TabsContent value="details">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Home className="h-5 w-5" />
                Tenancy Details
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="font-medium w-1/3">ID</TableCell>
                    <TableCell>{tenancy.id}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Reference</TableCell>
                    <TableCell>{tenancy.reference || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Property ID</TableCell>
                    <TableCell>{tenancy.property_id || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Property Reference</TableCell>
                    <TableCell>{(tenancy as any).property?.reference || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Address</TableCell>
                    <TableCell>
                      {(tenancy as any).property?.display_address || 
                       `${(tenancy as any).property?.address_line_1 || ''} ${(tenancy as any).property?.town_city || ''} ${(tenancy as any).property?.postcode || ''}`.trim() || '-'}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Start Date</TableCell>
                    <TableCell>{formatDate(tenancy.start_date)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">End Date</TableCell>
                    <TableCell>{formatDate(tenancy.end_date)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Status</TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(tenancy.status)} variant="secondary">
                        {tenancy.status || 'Unknown'}
                      </Badge>
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Is Periodic</TableCell>
                    <TableCell>{tenancy.is_periodic ? 'Yes' : 'No'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Is HMO</TableCell>
                    <TableCell>{tenancy.is_hmo ? 'Yes' : 'No'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Branch</TableCell>
                    <TableCell>{tenancy.branch || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Lead Staff</TableCell>
                    <TableCell>{tenancy.lead_staff || '-'}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Tenant Tab */}
        <TabsContent value="tenant">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <User className="h-5 w-5" />
                Tenant Information
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="font-medium w-1/3">Tenant ID</TableCell>
                    <TableCell>{tenancy.tenant_id || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Tenant Name</TableCell>
                    <TableCell>
                      {(tenancy as any).tenant
                        ? `${(tenancy as any).tenant.first_name} ${(tenancy as any).tenant.last_name}`
                        : '-'}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Email</TableCell>
                    <TableCell>{(tenancy as any).tenant?.email || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Phone Number</TableCell>
                    <TableCell>{(tenancy as any).tenant?.phone || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Company</TableCell>
                    <TableCell>{(tenancy as any).tenant?.company || '-'}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Financial Tab */}
        <TabsContent value="financial">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <PoundSterling className="h-5 w-5" />
                Financial Details
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="font-medium w-1/3">Rent</TableCell>
                    <TableCell>{formatCurrency(tenancy.rent)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Rent Payment Frequency</TableCell>
                    <TableCell>{tenancy.rent_payment_frequency || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Deposit</TableCell>
                    <TableCell>{formatCurrency(tenancy.deposit)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Where Deposit Held</TableCell>
                    <TableCell>{tenancy.where_deposit_held || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Letting Service</TableCell>
                    <TableCell>{tenancy.letting_service || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Letting Fee</TableCell>
                    <TableCell>{formatCurrency(tenancy.letting_fee)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Management Fee</TableCell>
                    <TableCell>{formatCurrency(tenancy.management_fee)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Is Rent Guaranteed</TableCell>
                    <TableCell>{tenancy.is_rent_guaranteed ? 'Yes' : 'No'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Rent Review Date</TableCell>
                    <TableCell>{formatDate(tenancy.rent_review_date)}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Terms Tab */}
        <TabsContent value="terms">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                Tenancy Terms
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="font-medium w-1/3">Renewal</TableCell>
                    <TableCell>{tenancy.renewal || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Break Clause</TableCell>
                    <TableCell>{tenancy.break_clause || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Notice Period</TableCell>
                    <TableCell>{tenancy.notice_period || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Special Clause</TableCell>
                    <TableCell className="whitespace-pre-wrap">
                      {tenancy.tenancy_agreement_special_clause || '-'}
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Rent Payments Tab */}
        <TabsContent value="rent">
          <RentPaymentsTab tenancyId={tenancy.id} />
        </TabsContent>

        {/* Documents Tab */}
        <TabsContent value="documents">
          <TenancyDocumentsTab tenancyId={tenancy.id} />
        </TabsContent>

        {/* Landlord Tab */}
        <TabsContent value="landlord">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Shield className="h-5 w-5" />
                Landlord Information
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="font-medium w-1/3">Landlord ID</TableCell>
                    <TableCell>{(tenancy as any).property?.landlord_id || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Landlord Name</TableCell>
                    <TableCell>
                      {landlord
                        ? `${landlord.first_name} ${landlord.last_name}`
                        : '-'}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Email</TableCell>
                    <TableCell>{landlord?.email || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Phone Number</TableCell>
                    <TableCell>{landlord?.phone || '-'}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="font-medium">Company</TableCell>
                    <TableCell>{landlord?.company || '-'}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Form Dialog */}
      <TenancyFormDialog
        open={formOpen}
        onOpenChange={setFormOpen}
        tenancy={tenancy as TenancyWithRelations}
      />

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Tenancy</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this tenancy? This action can be undone from the
              trash.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
