'use client';

import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { Edit3, FileCheck, FileText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useUpdateKycDocument } from '@/services/kyc/queries';

interface EditKycDocumentModalProps {
  documentId: string;
  documentType: string;
  currentDocumentName: string;
  userFullName: string;
  onClose: () => void;
  onSuccess?: () => void;
}

interface FormValues {
  file: File | null;
}

export default function EditKycDocumentModal({
  documentId,
  documentType,
  currentDocumentName,
  userFullName,
  onClose,
  onSuccess,
}: EditKycDocumentModalProps) {
  const [error, setError] = useState<string | null>(null);
  const updateMutation = useUpdateKycDocument();

  const { control, handleSubmit } = useForm<FormValues>({
    defaultValues: {
      file: null,
    },
  });

  const onSubmit = async (values: FormValues) => {
    setError(null);

    if (!values.file) {
      setError('Please select a replacement file before submitting.');
      return;
    }

    try {
      await updateMutation.mutateAsync({
        documentId,
        file: values.file,
      });
      if (onSuccess) onSuccess();
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message || 'Failed to update the KYC document.');
    }
  };

  return (
    <Modal onClose={onClose} icon={Edit3} title={`Replace Document: ${documentType.replace(/_/g, ' ')}`}>
      <form onSubmit={handleSubmit(onSubmit)} className="p-4 space-y-4 text-left">
        {/* Identity & Target Document Context */}
        <div className="p-3 rounded-lg bg-muted/30 border border-border/40 space-y-1.5 text-xs">
          <div className="flex items-center justify-between">
            <span className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">Target Identity</span>
            <span className="font-bold text-foreground">{userFullName}</span>
          </div>
          <div className="flex items-center justify-between border-t border-border/10 pt-1.5">
            <span className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">Current Asset</span>
            <span className="font-mono text-[11px] text-foreground truncate max-w-[200px]" title={currentDocumentName}>
              {currentDocumentName}
            </span>
          </div>
        </div>

        {error && (
          <div className="p-2.5 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium">
            {error}
          </div>
        )}

        {/* Replacement File Upload Input */}
        <div className="bg-muted/20 p-3 rounded-lg border border-border/30 space-y-1.5">
          <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">
            Select Replacement File (.pdf, .png, .jpg, .jpeg)
          </label>
          <Controller
            control={control}
            name="file"
            render={({ field: { onChange } }) => (
              <input
                type="file"
                accept=".pdf,.png,.jpg,.jpeg"
                onChange={(e) => onChange(e.target.files?.[0] || null)}
                className="w-full text-xs text-muted-foreground file:mr-2.5 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-[10px] file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20 cursor-pointer"
              />
            )}
          />
        </div>

        {/* Action Controls */}
        <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3 mt-4">
          <Button
            type="button"
            variant="ghost"
            onClick={onClose}
            className="h-8 rounded-lg px-3 text-xs font-semibold cursor-pointer"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={updateMutation.isPending}
            className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm gap-1.5 cursor-pointer"
          >
            <FileCheck className="h-3.5 w-3.5 stroke-[2.5]" />
            <span>{updateMutation.isPending ? 'Updating Asset...' : 'Upload Replacement'}</span>
          </Button>
        </div>
      </form>
    </Modal>
  );
}