'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Loader2,
  CheckCircle2,
  MapPin,
  Navigation,
  Milestone,
  ArrowUpCircle,
  ArrowDownCircle,
} from 'lucide-react';
import { DataTable } from '@/components/data-table';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { projectService, packageService, chainageService } from '@/services/api';
import { Project, Package as PackageType, Chainage, ChainageCreate, ChainageUpdate } from '@/types';
import { ColumnDef } from '@tanstack/react-table';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

export default function ChainagePage() {
  const [chainages, setChainages] = useState<Chainage[]>([]);
  const [totalItems, setTotalItems] = useState(0);
  const [projects, setProjects] = useState<Project[]>([]);
  const [packages, setPackages] = useState<PackageType[]>([]);
  const [allPackages, setAllPackages] = useState<PackageType[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loadingProjects, setLoadingProjects] = useState(false);
  const [loadingPackages, setLoadingPackages] = useState(false);

  // Pagination state
  const [skip, setSkip] = useState(0);
  const [limit, setLimit] = useState(10);

  // Editing state
  const [isEditing, setIsEditing] = useState(false);
  const [currentChainage, setCurrentChainage] = useState<Chainage | null>(null);

  // Form fields
  const [selectedProjectId, setSelectedProjectId] = useState('');
  const [selectedPackageId, setSelectedPackageId] = useState('');
  const [segmentName, setSegmentName] = useState('');
  const [chainageStartKm, setChainageStartKm] = useState('');
  const [chainageEndKm, setChainageEndKm] = useState('');
  const [startLat, setStartLat] = useState('');
  const [startLng, setStartLng] = useState('');
  const [endLat, setEndLat] = useState('');
  const [endLng, setEndLng] = useState('');
  const [direction, setDirection] = useState<'UP' | 'DOWN'>('UP');

  // Load chainages and projects
  const loadChainages = async (currentSkip = skip, currentLimit = limit) => {
    try {
      setIsLoading(true);
      setError(null);
      const data = await chainageService.getChainages({ skip: currentSkip, limit: currentLimit });
      setChainages(data.items);
      setTotalItems(data.totalItems);
    } catch (err) {
      setError('Failed to load segments. Please check if the backend is running.');
    } finally {
      // Add a small delay for animation stability
      setTimeout(() => {
        setIsLoading(false);
      }, 800);
    }
  };

  const loadProjects = async () => {
    try {
      setLoadingProjects(true);
      const data = await projectService.getProjects({ skip: 0, limit: 1000 });
      setProjects(data.items);
    } catch (err) {
      setError('Failed to load projects.');
    } finally {
      setLoadingProjects(false);
    }
  };

  const loadAllPackages = async () => {
    try {
      const data = await packageService.getPackages({ skip: 0, limit: 1000 });
      setAllPackages(data.items);
    } catch (err) {
      console.error('Failed to load all packages');
    }
  };

  useEffect(() => {
    loadChainages(skip, limit);
    loadProjects();
    loadAllPackages();
  }, [skip, limit]);

  // Load packages when project changes
  useEffect(() => {
    if (!selectedProjectId) {
      setPackages([]);
      if (!isEditing) setSelectedPackageId('');
      return;
    }

    const loadPackagesForProject = async () => {
      try {
        setLoadingPackages(true);
        if (!isEditing) setSelectedPackageId('');
        const data = await packageService.getPackagesByProject(selectedProjectId, {
          skip: 0,
          limit: 1000,
        });
        setPackages(data.items);
      } catch (err) {
        setError('Failed to load packages for the selected project.');
      } finally {
        setLoadingPackages(false);
      }
    };
    loadPackagesForProject();
  }, [selectedProjectId, isEditing]);

  const resetForm = () => {
    setSelectedProjectId('');
    setSelectedPackageId('');
    setSegmentName('');
    setChainageStartKm('');
    setChainageEndKm('');
    setStartLat('');
    setStartLng('');
    setEndLat('');
    setEndLng('');
    setDirection('UP');
    setError(null);
    setIsEditing(false);
    setCurrentChainage(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPackageId && !isEditing) {
      setError('Please select a project and package first');
      return;
    }
    if (!segmentName.trim()) {
      setError('Segment name is required');
      return;
    }
    if (!chainageStartKm || !chainageEndKm) {
      setError('Segment start and end values are required');
      return;
    }

    setIsSubmitting(true);
    setError(null);

    try {
      if (isEditing && currentChainage) {
        const data: ChainageUpdate = {
          segment_name: segmentName.trim(),
          chainage_start_km: parseFloat(chainageStartKm),
          chainage_end_km: parseFloat(chainageEndKm),
          start_lat: startLat ? parseFloat(startLat) : 0,
          start_lng: startLng ? parseFloat(startLng) : 0,
          end_lat: endLat ? parseFloat(endLat) : 0,
          end_lng: endLng ? parseFloat(endLng) : 0,
          direction: direction as 'UP' | 'DOWN',
        };
        await chainageService.updateChainage(currentChainage.id, data);
        toast.success('Segment Updated', {
          description: `${segmentName} has been updated successfully at ${new Date().toLocaleTimeString()}`,
        });
      } else {
        const data: ChainageCreate = {
          package_id: selectedPackageId,
          segment_name: segmentName.trim(),
          chainage_start_km: parseFloat(chainageStartKm),
          chainage_end_km: parseFloat(chainageEndKm),
          start_lat: startLat ? parseFloat(startLat) : 0,
          start_lng: startLng ? parseFloat(startLng) : 0,
          end_lat: endLat ? parseFloat(endLat) : 0,
          end_lng: endLng ? parseFloat(endLng) : 0,
          direction: direction,
        };
        await chainageService.createChainage(data);
        toast.success('Segment Created', {
          description: `${segmentName} has been established successfully at ${new Date().toLocaleTimeString()}`,
        });
      }

      // Refresh chainages list
      await loadChainages();

      // Close modal and reset form immediately
      setIsModalOpen(false);
      resetForm();
    } catch (err) {
      const message =
        err instanceof Error
          ? err.message
          : `Failed to ${isEditing ? 'update' : 'create'} segment`;
      setError(message);
      toast.error('Operation Failed', {
        description: message,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (chainage: Chainage) => {
    setIsEditing(true);
    setCurrentChainage(chainage);

    // Find project for this package
    const pkg = allPackages.find((p) => p.id === chainage.package_id);
    if (pkg) {
      setSelectedProjectId(pkg.project_id);
      setSelectedPackageId(chainage.package_id);
    }

    setSegmentName(chainage.segment_name || '');
    setChainageStartKm(chainage.chainage_start_km?.toString() || '');
    setChainageEndKm(chainage.chainage_end_km?.toString() || '');
    setStartLat(chainage.start_lat.toString());
    setStartLng(chainage.start_lng.toString());
    setEndLat(chainage.end_lat.toString());
    setEndLng(chainage.end_lng.toString());
    setDirection(chainage.direction);
    setIsModalOpen(true);
  };

  const handleDelete = async (chainage: Chainage) => {
    if (!confirm(`Are you sure you want to delete segment "${chainage.segment_name}"?`)) return;

    try {
      setIsLoading(true);
      await chainageService.deleteChainage(chainage.id);
      toast.success('Segment Deleted', {
        description: `${chainage.segment_name} has been removed from the system.`,
      });
      await loadChainages();
    } catch (err) {
      setError('Failed to delete segment');
      toast.error('Deletion Failed', {
        description: 'The segment could not be removed. Please try again.',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const getPackageName = (packageId: string) => {
    return allPackages.find((p) => p.id === packageId)?.name || packageId;
  };

  const isFormComplete =
    selectedPackageId &&
    segmentName.trim() &&
    chainageStartKm &&
    chainageEndKm;

  const columns: ColumnDef<Chainage>[] = [
    {
      accessorKey: 'segment_name',
      header: 'Segment Name',
      cell: ({ row }) => <div className="font-semibold">{row.original.segment_name}</div>,
    },
    {
      accessorKey: 'package_id',
      header: 'Package',
      cell: ({ row }) => getPackageName(row.original.package_id),
    },
    {
      accessorKey: 'project',
      header: 'Project',
      cell: ({ row }) => {
        const chainage = row.original;
        const pkg = allPackages.find((p) => p.id === chainage.package_id);
        const project = projects.find((p) => p.id === pkg?.project_id);
        return project?.name || '—';
      },
    },
    {
      id: 'project_state',
      header: 'Project State',
      cell: ({ row }) => {
        const chainage = row.original;
        const pkg = allPackages.find((p) => p.id === chainage.package_id);
        const project = projects.find((p) => p.id === pkg?.project_id);
        if (!project?.state) return <span className="">—</span>;

        const states = project.state
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean);
        if (states.length === 0) return <span className="">—</span>;

        const firstState = states[0];
        const remainingStates = states.slice(1);

        return (
          <div className="flex items-center gap-1.5">
            <Badge variant="secondary">{firstState}</Badge>

            {remainingStates.length > 0 && (
              <Popover>
                <PopoverTrigger asChild>
                  <button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
                    +{remainingStates.length}
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-2" align="start">
                  <div className="flex flex-col gap-1.5">
                    <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
                      Other States
                    </p>
                    {remainingStates.map((item, idx) => (
                      <Badge key={idx} variant="secondary">
                        {item}
                      </Badge>
                    ))}
                  </div>
                </PopoverContent>
              </Popover>
            )}
          </div>
        );
      },
    },
    {
      accessorKey: 'chainage',
      header: 'Segment Range (km)',
      cell: ({ row }) => {
        const chainage = row.original;
        return (
          <div className="flex flex-row gap-2">
            <Badge
              variant="outline"
              className="flex items-center gap-1.5 border-amber-500/50 text-amber-500 font-bold whitespace-nowrap"
            >
              <Milestone className="h-3 w-3" />
              {chainage.chainage_start_km} - {chainage.chainage_end_km}
            </Badge>
            <Badge variant="secondary">
              {chainage.direction === 'UP' ? (
                <ArrowUpCircle className="h-3 w-3" />
              ) : (
                <ArrowDownCircle className="h-3 w-3" />
              )}
              {chainage.direction}
            </Badge>
          </div>
        );
      },
    },
    {
      accessorKey: 'start_gps',
      header: 'Start GPS',
      cell: ({ row }) => (
        <Badge
          variant="outline"
          className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
        >
          <MapPin className="h-3 w-3" />
          {row.original.start_lat.toFixed(4)}, {row.original.start_lng.toFixed(4)}
        </Badge>
      ),
    },
    {
      accessorKey: 'end_gps',
      header: 'End GPS',
      cell: ({ row }) => (
        <Badge
          variant="outline"
          className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
        >
          <MapPin className="h-3 w-3" />
          {row.original.end_lat.toFixed(4)}, {row.original.end_lng.toFixed(4)}
        </Badge>
      ),
    },
  ];

  return (
    <>
      <main className="relative z-10">
        {/* Refined Header */}
        <div className="mb-8">
          <PageHeader
            title="Segment Management"
            description="Manage road segments"
            icon={Milestone}
            actions={
              <Button
                onClick={() => {
                  setIsEditing(false);
                  setIsModalOpen(true);
                }}
              >
                <Milestone className="mr-2 h-4 w-4" />
                Add Segment
              </Button>
            }
          />
        </div>

        {/* Data Table */}
        <div>
          <DataTable
            title="Segments"
            data={chainages}
            columns={columns}
            onEdit={handleEdit}
            onDelete={handleDelete}
            isLoading={isLoading}
            pagination={{
              skip,
              limit,
              totalItems,
              onPageChange: setSkip,
              onLimitChange: (newLimit) => {
                setLimit(newLimit);
                setSkip(0); // Reset skip when limit changes
              },
            }}
          />
        </div>

        <PoweredBy />
      </main>

      {/* Modal Dialog */}
      <Dialog
        open={isModalOpen}
        onOpenChange={(open) => {
          if (!open) {
            setIsModalOpen(false);
            resetForm();
          } else {
            setIsModalOpen(true);
          }
        }}
      >
        <DialogContent className="sm:max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
          <DialogHeader className="gap-2">
            <DialogTitle className="flex items-center gap-3 text-xl">
              <div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
                <Milestone className="h-5 w-5" />
              </div>
              {isEditing ? 'Edit Segment' : 'Create Segment'}
            </DialogTitle>
            <DialogDescription className="text-sm">
              {isEditing
                ? 'Update the technical specifications for your road segment.'
                : 'Select a project & package, then provide the essential segment data.'}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit} className="space-y-6">
            {!isEditing && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Step 1: Select Project */}
                <div className="space-y-3">
                  <div className="flex items-center gap-2.5">
                    <div className="w-5 h-5 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
                      01
                    </div>
                    <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
                      Select Project
                    </p>
                  </div>
                  <Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
                    <SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
                      {loadingProjects ? (
                        <div className="flex items-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin text-primary" />
                          <span className="text-muted-foreground text-xs">Loading...</span>
                        </div>
                      ) : (
                        <SelectValue placeholder="Choose a project..." />
                      )}
                    </SelectTrigger>
                    <SelectContent>
                      {projects.map((project) => (
                        <SelectItem key={project.id} value={project.id} className="py-2.5">
                          <span className="font-semibold">{project.name}</span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Step 2: Select Package */}
                <div
                  className={`space-y-3 ${selectedProjectId ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
                >
                  <div className="flex items-center gap-2.5">
                    <div
                      className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
                    >
                      02
                    </div>
                    <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
                      Select Package
                    </p>
                  </div>
                  <Select
                    value={selectedPackageId}
                    onValueChange={setSelectedPackageId}
                    disabled={!selectedProjectId}
                  >
                    <SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
                      {loadingPackages ? (
                        <div className="flex items-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin text-primary" />
                          <span className="text-muted-foreground text-xs">Loading...</span>
                        </div>
                      ) : (
                        <SelectValue
                          placeholder={
                            selectedProjectId ? 'Choose a package...' : 'Select project first'
                          }
                        />
                      )}
                    </SelectTrigger>
                    <SelectContent>
                      {packages.map((pkg) => (
                        <SelectItem key={pkg.id} value={pkg.id} className="py-2.5">
                          <span className="font-semibold">{pkg.name}</span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}

            {/* Step 3: Chainage Details */}
            <div
              className={`space-y-4 ${selectedPackageId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
            >
              {!isEditing && (
                <div className="flex items-center gap-2.5">
                  <div
                    className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedPackageId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
                  >
                    03
                  </div>
                  <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
                    Segment Information
                  </p>
                </div>
              )}

              {/* Segment Name & Chainage Row */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                <div className="space-y-2">
                  <Label
                    htmlFor="segment"
                    className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
                  >
                    Segment Name <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="segment"
                    value={segmentName}
                    onChange={(e) => setSegmentName(e.target.value)}
                    placeholder="e.g. Mumbai to Pune"
                    className="h-11 bg-muted/20 border-border/60"
                    required
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label
                      htmlFor="ch-start"
                      className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
                    >
                      Start (km) <span className="text-destructive">*</span>
                    </Label>
                    <Input
                      id="ch-start"
                      type="number"
                      step="any"
                      min="0"
                      value={chainageStartKm}
                      onChange={(e) => setChainageStartKm(e.target.value)}
                      placeholder="0.0"
                      className="h-11 bg-muted/20 border-border/60 text-sm font-mono"
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label
                      htmlFor="ch-end"
                      className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
                    >
                      End (km) <span className="text-destructive">*</span>
                    </Label>
                    <Input
                      id="ch-end"
                      type="number"
                      step="any"
                      min="0"
                      value={chainageEndKm}
                      onChange={(e) => setChainageEndKm(e.target.value)}
                      placeholder="1.0"
                      className="h-11 bg-muted/20 border-border/60 text-sm font-mono"
                      required
                    />
                  </div>
                </div>
              </div>

              {/* Direction Row */}
              <div className="space-y-3">
                <Label
                  htmlFor="direction"
                  className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
                >
                  Direction <span className="text-destructive">*</span>
                </Label>
                <Select value={direction} onValueChange={(val: 'UP' | 'DOWN') => setDirection(val)}>
                  <SelectTrigger className="h-11 bg-muted/20 border-border/60 focus:ring-primary/20">
                    <SelectValue placeholder="Select Direction" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="UP" className="py-2.5">
                      <span>UP</span>
                    </SelectItem>
                    <SelectItem value="DOWN" className="py-2.5">
                      <span>DOWN</span>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* GPS Coordinates Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-5 pt-4">
                <div className="space-y-3 rounded-lg border border-border/50 bg-muted/10 p-4">
                  <p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
                    <MapPin className="h-3.5 w-3.5 opacity-60" /> START COORDINATES
                  </p>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label
                        htmlFor="s-lat"
                        className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
                      >
                        Latitude
                      </Label>
                      <Input
                        id="s-lat"
                        type="number"
                        step="any"
                        value={startLat}
                        onChange={(e) => setStartLat(e.target.value)}
                        placeholder="0.0000"
                        className="h-10 bg-background/70 border-border/40 text-xs font-mono"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label
                        htmlFor="s-lng"
                        className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
                      >
                        Longitude
                      </Label>
                      <Input
                        id="s-lng"
                        type="number"
                        step="any"
                        value={startLng}
                        onChange={(e) => setStartLng(e.target.value)}
                        placeholder="0.0000"
                        className="h-10 bg-background/70 border-border/40 text-xs font-mono"
                      />
                    </div>
                  </div>
                </div>

                <div className="space-y-3 rounded-lg border border-border/50 bg-muted/10 p-4">
                  <p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
                    <MapPin className="h-3.5 w-3.5 opacity-60" /> END COORDINATES
                  </p>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label
                        htmlFor="e-lat"
                        className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
                      >
                        Latitude
                      </Label>
                      <Input
                        id="e-lat"
                        type="number"
                        step="any"
                        value={endLat}
                        onChange={(e) => setEndLat(e.target.value)}
                        placeholder="0.0000"
                        className="h-10 bg-background/70 border-border/40 text-xs font-mono"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label
                        htmlFor="e-lng"
                        className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
                      >
                        Longitude
                      </Label>
                      <Input
                        id="e-lng"
                        type="number"
                        step="any"
                        value={endLng}
                        onChange={(e) => setEndLng(e.target.value)}
                        placeholder="0.0000"
                        className="h-10 bg-background/70 border-border/40 text-xs font-mono"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Submit Button */}
            <div className="flex gap-4 pt-4">
              <Button
                className="flex-1"
                type="button"
                variant="outline"
                onClick={() => {
                  setIsModalOpen(false);
                  resetForm();
                }}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting || !isFormComplete} className="flex-1">
                {isSubmitting ? (
                  <div className="flex items-center gap-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span>{isEditing ? 'Updating...' : 'Creating...'}</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    {isEditing ? (
                      <CheckCircle2 className="h-4 w-4" />
                    ) : (
                      <Milestone className="h-4 w-4" />
                    )}
                    <span>{isEditing ? 'Update Segment' : 'Create Segment'}</span>
                  </div>
                )}
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </>
  );
}
