'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  BarChart3,
  RefreshCw,
  Users,
  MapPin,
  Settings2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Slider } from '@/components/ui/slider';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Progress } from '@/components/ui/progress';
import { authFetch } from '@/lib/api';

interface EngineerWorkload {
  id: string;
  name: string;
  email: string;
  area: string | undefined;
  totalAssigned: number;
  statusBreakdown: Record<string, number>;
}

interface AreaInfo {
  id: string;
  name: string;
  code: string;
}

export default function WorkloadSettings() {
  const { t } = useTranslation();
  const [engineers, setEngineers] = useState<EngineerWorkload[]>([]);
  const [areas, setAreas] = useState<AreaInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [globalLimit, setGlobalLimit] = useState(15);
  const [roleLimits, setRoleLimits] = useState<Record<string, number>>({
    service_engineer: 10,
    head_of_department: 20,
    vendor: 15,
  });
  const [autoAssign, setAutoAssign] = useState(true);
  const [balanceThreshold, setBalanceThreshold] = useState(3);
  const [saving, setSaving] = useState(false);
  const [selectedArea, setSelectedArea] = useState('all');

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [engRes, areasRes, settingsRes] = await Promise.all([
        authFetch('/api/reports?type=engineer_performance'),
        authFetch('/api/areas'),
        authFetch('/api/settings?category=workload'),
      ]);

      if (engRes.ok) {
        const data = await engRes.json();
        setEngineers(data.data || []);
      }

      if (areasRes.ok) {
        const data = await areasRes.json();
        setAreas((data.areas || []).map((a: AreaInfo) => ({ id: a.id, name: a.name, code: a.code })));
      }

      if (settingsRes.ok) {
        const data = await settingsRes.json();
        const settings = data.settings || {};
        if (settings.globalWorkloadLimit) setGlobalLimit(Number(settings.globalWorkloadLimit));
        if (settings.autoAssign === 'true' || settings.autoAssign === true) setAutoAssign(true);
        if (settings.autoAssign === 'false' || settings.autoAssign === false) setAutoAssign(false);
        if (settings.balanceThreshold) setBalanceThreshold(Number(settings.balanceThreshold));
      }
    } catch (err) {
      console.error('Fetch workload error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const saveSettings = async () => {
    setSaving(true);
    try {
      await authFetch('/api/settings', {
        method: 'PUT',
        body: JSON.stringify({
          settings: [
            { key: 'globalWorkloadLimit', value: String(globalLimit), category: 'workload' },
            { key: 'autoAssign', value: String(autoAssign), category: 'workload' },
            { key: 'balanceThreshold', value: String(balanceThreshold), category: 'workload' },
            { key: 'roleLimits', value: JSON.stringify(roleLimits), category: 'workload' },
          ],
        }),
      });
    } catch (err) {
      console.error('Save settings error:', err);
    } finally {
      setSaving(false);
    }
  };

  const filteredEngineers = selectedArea === 'all'
    ? engineers
    : engineers.filter((e) => e.area === areas.find((a) => a.id === selectedArea)?.name);

  const areaWorkload = areas.map((area) => {
    const areaEngs = engineers.filter((e) => e.area === area.name);
    const total = areaEngs.reduce((sum, e) => sum + e.totalAssigned, 0);
    return { ...area, total, engineers: areaEngs.length };
  });

  return (
    <div className="space-y-6 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.workload}</h1>
          <p className="text-sm text-muted-foreground">{t.workload.workloadOverview} &amp; configuration</p>
        </div>
        <Button onClick={saveSettings} disabled={saving} className="bg-emerald-600 hover:bg-emerald-700">
          {saving ? t.common.loading : t.actions.save}
        </Button>
      </div>

      {/* Global Settings */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Settings2 className="w-4 h-4 text-emerald-600" /> Global Workload Settings
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label className="text-sm">Global Workload Limit</Label>
              <span className="text-lg font-bold text-emerald-600">{globalLimit}</span>
            </div>
            <Slider
              value={[globalLimit]}
              onValueChange={(v) => setGlobalLimit(v[0])}
              max={50}
              min={1}
              step={1}
            />
            <p className="text-xs text-muted-foreground">Maximum complaints per engineer across the system</p>
          </div>

          <Separator />

          {/* Auto-Assignment */}
          <div className="flex items-center justify-between">
            <div>
              <Label className="text-sm">Auto-Assignment</Label>
              <p className="text-xs text-muted-foreground">Automatically assign complaints to available engineers</p>
            </div>
            <Switch checked={autoAssign} onCheckedChange={setAutoAssign} />
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label className="text-sm">Balance Threshold</Label>
              <span className="text-sm font-medium">{balanceThreshold}</span>
            </div>
            <Slider
              value={[balanceThreshold]}
              onValueChange={(v) => setBalanceThreshold(v[0])}
              max={10}
              min={1}
              step={1}
            />
            <p className="text-xs text-muted-foreground">Max difference in workload between engineers before balancing</p>
          </div>
        </CardContent>
      </Card>

      {/* Per-Role Limits */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Per-Role Workload Limits</CardTitle>
          <CardDescription>Set workload limits for each user role</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {Object.entries(roleLimits).map(([role, limit]) => (
            <div key={role} className="space-y-2">
              <div className="flex items-center justify-between">
                <Label className="text-sm capitalize">{role.replace(/_/g, ' ')}</Label>
                <span className="text-sm font-bold text-emerald-600">{limit}</span>
              </div>
              <Slider
                value={[limit]}
                onValueChange={(v) => setRoleLimits((prev) => ({ ...prev, [role]: v[0] }))}
                max={50}
                min={1}
                step={1}
              />
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Area-Wise Distribution */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <MapPin className="w-4 h-4 text-emerald-600" /> Area-Wise Workload Distribution
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
            {areaWorkload.map((area) => (
              <div key={area.id} className="p-3 border rounded-lg hover:border-emerald-300 transition-colors">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium">{area.name}</span>
                  <Badge variant="outline" className="text-[10px]">{area.engineers} eng.</Badge>
                </div>
                <div className="flex items-center gap-2">
                  <Progress value={Math.min((area.total / Math.max(area.engineers * globalLimit, 1)) * 100, 100)} className="h-2 flex-1" />
                  <span className="text-xs font-medium">{area.total}</span>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Engineer Availability */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-base flex items-center gap-2">
              <Users className="w-4 h-4 text-emerald-600" /> Engineer Availability & Workload
            </CardTitle>
            <Select value={selectedArea} onValueChange={setSelectedArea}>
              <SelectTrigger className="w-[160px] h-8">
                <SelectValue placeholder="Filter area" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Areas</SelectItem>
                {areas.map((a) => (
                  <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground text-center py-4">{t.common.loading}</p>
          ) : filteredEngineers.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-4">{t.common.noData}</p>
          ) : (
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {filteredEngineers.map((eng) => {
                const active = (eng.statusBreakdown.assigned || 0) + (eng.statusBreakdown.in_progress || 0);
                const resolved = (eng.statusBreakdown.resolved || 0) + (eng.statusBreakdown.closed || 0);
                const pct = Math.min((active / globalLimit) * 100, 100);

                return (
                  <div key={eng.id} className="p-3 border rounded-lg hover:border-emerald-300 transition-colors">
                    <div className="flex items-center justify-between mb-1.5">
                      <div>
                        <p className="text-sm font-medium">{eng.name}</p>
                        <p className="text-xs text-muted-foreground">{eng.area || 'No area'}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge variant={active >= globalLimit ? 'destructive' : 'outline'} className="text-[10px]">
                          {active}/{globalLimit}
                        </Badge>
                        <Badge variant="secondary" className="text-[10px] bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300">
                          {resolved} done
                        </Badge>
                      </div>
                    </div>
                    <Progress value={pct} className="h-1.5" />
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
