'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  Plus,
  MapPin,
  Users,
  Wrench,
  UserCog,
  Pencil,
  Building2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { authFetch } from '@/lib/api';
import DataPagination from '@/components/shared/DataPagination';

interface AreaData {
  id: string;
  name: string;
  nameBn?: string;
  code: string;
  latitude?: number;
  longitude?: number;
  isActive: boolean;
  _count?: {
    complaints: number;
    engineers: number;
    hod: number;
  };
}

interface UserData {
  id: string;
  name: string;
  email: string;
  role: string;
}

export default function AreaManager() {
  const { t } = useTranslation();
  const [areas, setAreas] = useState<AreaData[]>([]);
  const [loading, setLoading] = useState(true);
  const [addOpen, setAddOpen] = useState(false);
  const [editArea, setEditArea] = useState<AreaData | null>(null);
  const [saving, setSaving] = useState(false);
  const [page, setPage] = useState(1);
  const AREAS_PER_PAGE = 12;
  const [hodUsers, setHodUsers] = useState<UserData[]>([]);
  const [engineerUsers, setEngineerUsers] = useState<UserData[]>([]);

  const [formName, setFormName] = useState('');
  const [formNameBn, setFormNameBn] = useState('');
  const [formCode, setFormCode] = useState('');
  const [formLat, setFormLat] = useState('');
  const [formLng, setFormLng] = useState('');

  const fetchAreas = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/areas');
      if (res.ok) {
        const data = await res.json();
        setAreas(data.areas || []);
        setPage(1);
      }
    } catch (err) {
      console.error('Fetch areas error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchUsersForAssignment = useCallback(async () => {
    try {
      const [hodRes, engRes] = await Promise.all([
        authFetch('/api/users?role=head_of_department&limit=100'),
        authFetch('/api/users?role=service_engineer&limit=100'),
      ]);
      if (hodRes.ok) {
        const data = await hodRes.json();
        setHodUsers(data.users || []);
      }
      if (engRes.ok) {
        const data = await engRes.json();
        setEngineerUsers(data.users || []);
      }
    } catch (err) {
      console.error('Fetch users error:', err);
    }
  }, []);

  useEffect(() => {
    fetchAreas();
    fetchUsersForAssignment();
  }, [fetchAreas, fetchUsersForAssignment]);

  const resetForm = () => {
    setFormName('');
    setFormNameBn('');
    setFormCode('');
    setFormLat('');
    setFormLng('');
  };

  const openAdd = () => {
    resetForm();
    setEditArea(null);
    setAddOpen(true);
  };

  const openEdit = (area: AreaData) => {
    setEditArea(area);
    setFormName(area.name);
    setFormNameBn(area.nameBn || '');
    setFormCode(area.code);
    setFormLat(area.latitude?.toString() || '');
    setFormLng(area.longitude?.toString() || '');
    setAddOpen(true);
  };

  const totalPages = Math.ceil(areas.length / AREAS_PER_PAGE);
  const paginatedAreas = areas.slice((page - 1) * AREAS_PER_PAGE, page * AREAS_PER_PAGE);

  const handleSave = async () => {
    setSaving(true);
    try {
      if (editArea) {
        await authFetch(`/api/areas`, {
          method: 'PUT',
          body: JSON.stringify({
            id: editArea.id,
            name: formName,
            nameBn: formNameBn,
            code: formCode,
            latitude: formLat ? parseFloat(formLat) : null,
            longitude: formLng ? parseFloat(formLng) : null,
          }),
        });
      } else {
        await authFetch('/api/areas', {
          method: 'POST',
          body: JSON.stringify({
            name: formName,
            nameBn: formNameBn,
            code: formCode,
            latitude: formLat ? parseFloat(formLat) : null,
            longitude: formLng ? parseFloat(formLng) : null,
          }),
        });
      }
      setAddOpen(false);
      resetForm();
      fetchAreas();
    } catch (err) {
      console.error('Save area error:', err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-4 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold">{t.nav.areas}</h1>
          <p className="text-sm text-muted-foreground">Manage areas, assignments, and locations</p>
        </div>
        <Button onClick={openAdd} className="bg-emerald-600 hover:bg-emerald-700">
          <Plus className="w-4 h-4 mr-2" /> {t.actions.add} Area
        </Button>
      </div>

      {loading ? (
        <div className="p-8 text-center text-muted-foreground">{t.common.loading}</div>
      ) : areas.length === 0 ? (
        <div className="p-8 text-center text-muted-foreground">{t.common.noData}</div>
      ) : (
        <>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {paginatedAreas.map((area) => (
            <Card
              key={area.id}
              className="hover:shadow-lg transition-all duration-300 border-l-4 border-l-emerald-500 group"
            >
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/30 flex items-center justify-center">
                      <MapPin className="w-4 h-4 text-emerald-600" />
                    </div>
                    <div>
                      <CardTitle className="text-sm font-semibold">{area.name}</CardTitle>
                      <p className="text-[10px] text-muted-foreground font-mono">{area.code}</p>
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
                    onClick={() => openEdit(area)}
                  >
                    <Pencil className="w-3.5 h-3.5" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="pt-0">
                {area.nameBn && (
                  <p className="text-xs text-muted-foreground mb-2">{area.nameBn}</p>
                )}
                <div className="grid grid-cols-3 gap-2 mt-2">
                  <div className="text-center p-2 bg-muted/50 rounded-lg">
                    <MessageBubble className="w-3.5 h-3.5 mx-auto text-emerald-600 mb-1" />
                    <p className="text-lg font-bold">{area._count?.complaints || 0}</p>
                    <p className="text-[9px] text-muted-foreground">Complaints</p>
                  </div>
                  <div className="text-center p-2 bg-muted/50 rounded-lg">
                    <Wrench className="w-3.5 h-3.5 mx-auto text-orange-600 mb-1" />
                    <p className="text-lg font-bold">{area._count?.engineers || 0}</p>
                    <p className="text-[9px] text-muted-foreground">Engineers</p>
                  </div>
                  <div className="text-center p-2 bg-muted/50 rounded-lg">
                    <UserCog className="w-3.5 h-3.5 mx-auto text-blue-600 mb-1" />
                    <p className="text-lg font-bold">{area._count?.hod || 0}</p>
                    <p className="text-[9px] text-muted-foreground">HODs</p>
                  </div>
                </div>

                {/* Map Placeholder */}
                <div className="mt-3 h-24 bg-gradient-to-br from-emerald-50 to-emerald-100 dark:from-emerald-950/20 dark:to-emerald-900/20 rounded-lg flex items-center justify-center border border-emerald-200 dark:border-emerald-800">
                  <div className="text-center">
                    <MapPin className="w-5 h-5 text-emerald-400 mx-auto mb-1" />
                    <p className="text-[10px] text-emerald-600">
                      {area.latitude && area.longitude
                        ? `${area.latitude.toFixed(4)}, ${area.longitude.toFixed(4)}`
                        : 'No GIS location set'}
                    </p>
                  </div>
                </div>

                <div className="flex items-center justify-between mt-2">
                  <Badge variant={area.isActive ? 'default' : 'secondary'} className="text-[10px]">
                    {area.isActive ? 'Active' : 'Inactive'}
                  </Badge>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
        <DataPagination
          page={page}
          totalPages={totalPages}
          total={areas.length}
          onPageChange={setPage}
          limit={AREAS_PER_PAGE}
        />
        </>
      )}

      {/* Add/Edit Area Dialog */}
      <Dialog open={addOpen} onOpenChange={setAddOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editArea ? `Edit Area: ${editArea.name}` : 'Add New Area'}</DialogTitle>
            <DialogDescription>{editArea ? 'Update area information' : 'Create a new service area'}</DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">Name (English) *</Label>
                <Input value={formName} onChange={(e) => setFormName(e.target.value)} placeholder="Area name" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Name (Bengali)</Label>
                <Input value={formNameBn} onChange={(e) => setFormNameBn(e.target.value)} placeholder="এলাকার নাম" />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Area Code *</Label>
              <Input value={formCode} onChange={(e) => setFormCode(e.target.value.toUpperCase())} placeholder="e.g. DHK-01" disabled={!!editArea} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">Latitude</Label>
                <Input type="number" step="0.0001" value={formLat} onChange={(e) => setFormLat(e.target.value)} placeholder="23.8103" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Longitude</Label>
                <Input type="number" step="0.0001" value={formLng} onChange={(e) => setFormLng(e.target.value)} placeholder="90.4125" />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setAddOpen(false)}>{t.actions.cancel}</Button>
            <Button onClick={handleSave} disabled={saving || !formName || !formCode} className="bg-emerald-600 hover:bg-emerald-700">
              {saving ? t.common.loading : t.actions.save}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function MessageBubble(props: React.SVGProps<SVGSVGElement> & { className?: string }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...props}
    >
      <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
    </svg>
  );
}
