import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { format, addDays, isBefore } from 'date-fns';
import { Home, User, Calendar, PoundSterling, ExternalLink, ClipboardCheck, AlertTriangle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/AuthContext';

interface PropertyTenanciesTabProps {
  propertyId: string;
}

export function PropertyTenanciesTab({ propertyId }: PropertyTenanciesTabProps) {
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const [inspectionDialogOpen, setInspectionDialogOpen] = useState(false);
  const [selectedTenancyId, setSelectedTenancyId] = useState<string | null>(null);

  const { data: tenancies = [], isLoading } = useQuery({
    queryKey: ['property-tenancies', propertyId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('tenancies')
        .select(`
          *,
          tenant:contacts!tenancies_tenant_id_fkey(id, first_name, last_name, email, phone)
        `)
        .eq('property_id', propertyId)
        .is('deleted_at', null)
        .order('start_date', { ascending: false });

      if (error) throw error;
      return data;
    },
  });

  const recordInspectionMutation = useMutation({
    mutationFn: async (tenancyId: string) => {
      const today = new Date().toISOString().split('T')[0];
      const { error } = await supabase
        .from('tenancies')
        .update({ last_inspection_date: today })
        .eq('id', tenancyId);

      if (error) throw error;

      // Log activity
      if (user) {
        await supabase.from('activities').insert({
          type: 'system',
          direction: 'log',
          subject: 'Inspection Completed',
          body_preview: `Property inspection recorded on ${format(new Date(), 'dd MMM yyyy')}`,
          user_id: user.id,
          property_id: propertyId,
          category: 'inspection',
        });
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['property-tenancies', propertyId] });
      queryClient.invalidateQueries({ queryKey: ['tenancy-alerts'] });
      toast.success('Inspection recorded successfully');
      setInspectionDialogOpen(false);
      setSelectedTenancyId(null);
    },
    onError: (error) => {
      toast.error('Failed to record inspection: ' + error.message);
    },
  });

  const activeTenancies = tenancies.filter(t => t.status === 'active');
  const historicalTenancies = tenancies.filter(t => t.status !== 'active');

  const getStatusBadge = (status: string | null) => {
    switch (status) {
      case 'active':
        return <Badge className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Active</Badge>;
      case 'pending':
        return <Badge className="bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">Pending</Badge>;
      case 'ended':
        return <Badge className="bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200">Ended</Badge>;
      case 'cancelled':
        return <Badge className="bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">Cancelled</Badge>;
      default:
        return <Badge variant="outline">{status || 'Unknown'}</Badge>;
    }
  };

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

  const getNextInspectionDate = (tenancy: any) => {
    if (!tenancy.inspection_frequency || !tenancy.last_inspection_date) {
      return null;
    }
    return addDays(new Date(tenancy.last_inspection_date), tenancy.inspection_frequency);
  };

  const isInspectionDue = (tenancy: any) => {
    const nextDate = getNextInspectionDate(tenancy);
    if (!nextDate) return false;
    return isBefore(nextDate, addDays(new Date(), 30));
  };

  const handleRecordInspection = (tenancyId: string) => {
    setSelectedTenancyId(tenancyId);
    setInspectionDialogOpen(true);
  };

  const confirmRecordInspection = () => {
    if (selectedTenancyId) {
      recordInspectionMutation.mutate(selectedTenancyId);
    }
  };

  if (isLoading) {
    return (
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* Active Tenancies */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Home className="h-5 w-5" />
            Active Tenancies ({activeTenancies.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {activeTenancies.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <Home className="h-12 w-12 text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No active tenancies</p>
            </div>
          ) : (
            <div className="space-y-4">
              {activeTenancies.map((tenancy) => {
                const nextInspection = getNextInspectionDate(tenancy);
                const inspectionOverdue = isInspectionDue(tenancy);
                
                return (
                  <div key={tenancy.id} className="border rounded-lg p-4">
                    <div className="flex items-start justify-between">
                      <div className="space-y-2 flex-1">
                        <div className="flex items-center gap-2">
                          <h4 className="font-medium">{tenancy.reference || 'No Reference'}</h4>
                          {getStatusBadge(tenancy.status)}
                          {inspectionOverdue && (
                            <Badge variant="destructive" className="flex items-center gap-1">
                              <AlertTriangle className="h-3 w-3" />
                              Inspection Due
                            </Badge>
                          )}
                        </div>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                          <div className="flex items-center gap-2">
                            <User className="h-4 w-4 text-muted-foreground" />
                            <span>
                              {(tenancy as any).tenant
                                ? `${(tenancy as any).tenant.first_name} ${(tenancy as any).tenant.last_name}`
                                : 'No tenant'}
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            <Calendar className="h-4 w-4 text-muted-foreground" />
                            <span>{formatDate(tenancy.start_date)} - {formatDate(tenancy.end_date)}</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <PoundSterling className="h-4 w-4 text-muted-foreground" />
                            <span>
                              {tenancy.rent ? `£${Number(tenancy.rent).toLocaleString()}` : 'N/A'}
                              {tenancy.rent_payment_frequency && ` / ${tenancy.rent_payment_frequency}`}
                            </span>
                          </div>
                          {tenancy.inspection_frequency && (
                            <div className="flex items-center gap-2">
                              <ClipboardCheck className="h-4 w-4 text-muted-foreground" />
                              <span className="text-xs">
                                Last: {tenancy.last_inspection_date ? formatDate(tenancy.last_inspection_date) : 'Never'}
                                {nextInspection && ` | Next: ${format(nextInspection, 'dd MMM yyyy')}`}
                              </span>
                            </div>
                          )}
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => handleRecordInspection(tenancy.id)}
                        >
                          <ClipboardCheck className="mr-2 h-4 w-4" />
                          Record Inspection
                        </Button>
                        <Button variant="outline" size="sm" asChild>
                          <Link to={`/tenancies/${tenancy.id}`}>
                            <ExternalLink className="mr-2 h-4 w-4" />
                            View
                          </Link>
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Tenancy History */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            Tenancy History ({historicalTenancies.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {historicalTenancies.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <Calendar className="h-12 w-12 text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No historical tenancies</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Reference</TableHead>
                  <TableHead>Tenant</TableHead>
                  <TableHead>Start Date</TableHead>
                  <TableHead>End Date</TableHead>
                  <TableHead>Rent</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {historicalTenancies.map((tenancy) => (
                  <TableRow key={tenancy.id}>
                    <TableCell className="font-medium">
                      {tenancy.reference || '-'}
                    </TableCell>
                    <TableCell>
                      {(tenancy as any).tenant
                        ? `${(tenancy as any).tenant.first_name} ${(tenancy as any).tenant.last_name}`
                        : '-'}
                    </TableCell>
                    <TableCell>{formatDate(tenancy.start_date)}</TableCell>
                    <TableCell>{formatDate(tenancy.end_date)}</TableCell>
                    <TableCell>
                      {tenancy.rent ? `£${Number(tenancy.rent).toLocaleString()}` : '-'}
                    </TableCell>
                    <TableCell>{getStatusBadge(tenancy.status)}</TableCell>
                    <TableCell>
                      <Button variant="ghost" size="sm" asChild>
                        <Link to={`/tenancies/${tenancy.id}`}>
                          <ExternalLink className="h-4 w-4" />
                        </Link>
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Inspection Confirmation Dialog */}
      <AlertDialog open={inspectionDialogOpen} onOpenChange={setInspectionDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Record Inspection</AlertDialogTitle>
            <AlertDialogDescription>
              This will record an inspection as completed today ({format(new Date(), 'dd MMM yyyy')}). 
              The next inspection due date will be calculated based on the inspection frequency.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmRecordInspection}>
              Confirm Inspection
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}