"use client";

import React, { useState, forwardRef } from 'react';
import { ArrowRight, X, ChevronDown } from 'lucide-react';

// Input Component
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: string;
}

const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ label, error, className = '', ...props }, ref) => {
    return (
      <div className="mb-4">
        <label className="block text-gray-800 text-sm font-medium mb-2">
          {label}
        </label>
        <input
          ref={ref}
          className={`
            w-full px-6 py-4 rounded-full border border-gray-300 
            focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent
            transition-all duration-200 ease-in-out
            placeholder-gray-400 text-gray-700
            ${error ? 'border-red-500 ring-2 ring-red-200' : ''}
            ${className}
          `}
          {...props}
        />
        {error && (
          <p className="mt-1 text-sm text-red-600">{error}</p>
        )}
      </div>
    );
  }
);

Input.displayName = 'Input';

// Select Component
interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  label: string;
  error?: string;
  options: { value: string; label: string }[];
}

const Select = forwardRef<HTMLSelectElement, SelectProps>(
  ({ label, error, options, className = '', ...props }, ref) => {
    return (
      <div className="mb-4">
        <label className="block text-gray-800 text-sm font-medium mb-2">
          {label}
        </label>
        <div className="relative">
          <select
            ref={ref}
            className={`
              w-full px-6 py-4 rounded-full border border-gray-300 
              focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent
              transition-all duration-200 ease-in-out
              appearance-none bg-white text-gray-700
              ${error ? 'border-red-500 ring-2 ring-red-200' : ''}
              ${className}
            `}
            {...props}
          >
            {options.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" size={20} />
        </div>
        {error && (
          <p className="mt-1 text-sm text-red-600">{error}</p>
        )}
      </div>
    );
  }
);

Select.displayName = 'Select';

// Main Component
export default function ApplyForLoan() {
  const [formData, setFormData] = useState({
    employmentStatus: 'Employed',
    stateOfResidence: 'Calabar',
    guarantorName: 'Gamble',
    relationshipStatus: '',
    guarantorPhone: '081245346789',
    loanPurpose: 'House rent',
    loanAmount: '5000',
    loanTenure: '6',
  });

  const [loanDetails] = useState({
    loanAmount: 50000,
    interest: 3000,
    totalAmountDue: 53000,
    dueDate: '12 OCT 2025',
    dueAmount: 8833,
    monthlyRepayment: 8833,
    installments: 6,
    duration: 180,
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleContinue = () => {
    console.log('Form submitted:', formData);
  };

  const handleCancel = () => {
    console.log('Form cancelled');
  };

  const employmentOptions = [
    { value: 'Employed', label: 'Employed' },
    { value: 'Self-Employed', label: 'Self-Employed' },
    { value: 'Unemployed', label: 'Unemployed' },
  ];

  const stateOptions = [
    { value: 'Calabar', label: 'Calabar' },
    { value: 'Lagos', label: 'Lagos' },
    { value: 'Abuja', label: 'Abuja' },
  ];

  const tenureOptions = [
    { value: '3', label: '3 months' },
    { value: '6', label: '6 months' },
    { value: '12', label: '12 months' },
  ];

  return (
    <div className="min-h-screen bg-gray-50 p-4 sm:p-8">
      <div className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-[1.5fr_1fr] gap-8">
        {/* Left Column - Form */}
        <div className="bg-white rounded-3xl shadow-sm p-6 sm:p-8">
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">
            Apply for loan
          </h1>
          <p className="text-gray-600 mb-8">
            Invest towards any personal or financial goal of your choice
          </p>

          <div className="space-y-6">
            <Select
              label="Employment Status"
              name="employmentStatus"
              value={formData.employmentStatus}
              onChange={handleInputChange}
              options={employmentOptions}
            />

            <Select
              label="State of Residence"
              name="stateOfResidence"
              value={formData.stateOfResidence}
              onChange={handleInputChange}
              options={stateOptions}
            />

            <Input
              label="Guarantor's Name"
              name="guarantorName"
              value={formData.guarantorName}
              onChange={handleInputChange}
              placeholder="Enter guarantor's name"
            />

            <Input
              label="Relationship Status"
              name="relationshipStatus"
              value={formData.relationshipStatus}
              onChange={handleInputChange}
              placeholder="Enter relationship status"
            />

            <Input
              label="Guarantor's Phone Number"
              name="guarantorPhone"
              type="tel"
              value={formData.guarantorPhone}
              onChange={handleInputChange}
              placeholder="Enter phone number"
            />

            <Input
              label="Loan Purpose"
              name="loanPurpose"
              value={formData.loanPurpose}
              onChange={handleInputChange}
              placeholder="Enter loan purpose"
            />

            <Input
              label="Loan Amount"
              name="loanAmount"
              type="number"
              value={formData.loanAmount}
              onChange={handleInputChange}
              placeholder="Enter amount"
            />

            <Select
              label="Loan Tenure"
              name="loanTenure"
              value={formData.loanTenure}
              onChange={handleInputChange}
              options={tenureOptions}
            />

            <div className="flex gap-4 pt-6">
              <button
                type="button"
                onClick={handleContinue}
                className="flex-1 bg-purple-700 text-white py-3.5 px-6 rounded-xl font-medium hover:bg-purple-800 transition flex items-center justify-center gap-2"
              >
                <ArrowRight size={20} />
                Continue
              </button>
              <button
                type="button"
                onClick={handleCancel}
                className="flex-1 bg-white border-2 border-gray-200 text-gray-700 py-3.5 px-6 rounded-xl font-medium hover:bg-gray-50 transition flex items-center justify-center gap-2"
              >
                <X size={20} />
                Cancel
              </button>
            </div>
          </div>
        </div>

        {/* Right Column - Review Card */}
        <div className="bg-white rounded-3xl shadow-sm p-6 sm:p-8 h-fit lg:sticky lg:top-8">
          <h2 className="text-xl font-semibold text-gray-900 text-center mb-4">
            Review
          </h2>
          
          <div className="text-center mb-6">
            <p className="text-4xl font-bold text-gray-900 mb-2">
              N{loanDetails.loanAmount.toLocaleString()}
            </p>
            <p className="text-sm text-gray-600 mb-1">
              by {loanDetails.dueDate}
            </p>
            <p className="text-sm text-purple-700 flex items-center justify-center gap-1">
              <span className="w-2 h-2 bg-purple-700 rounded-full"></span>
              {loanDetails.installments} installments for {loanDetails.duration} days
            </p>
          </div>

          <div className="space-y-4 border-t border-gray-100 pt-6 mb-6">
            <div className="flex justify-between items-center">
              <span className="text-gray-600 text-sm">LOAN AMOUNT</span>
              <span className="text-gray-900 font-medium">
                N{loanDetails.loanAmount.toLocaleString()}.00
              </span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-gray-600 text-sm">INTEREST</span>
              <span className="text-gray-900 font-medium">
                N{loanDetails.interest.toLocaleString()}.00
              </span>
            </div>
            
            <div className="flex justify-between items-center pb-4 border-b border-gray-100">
              <span className="text-gray-600 text-sm">TOTAL AMOUNT DUE</span>
              <span className="text-gray-900 font-semibold">
                N{loanDetails.totalAmountDue.toLocaleString()}.00
              </span>
            </div>

            <div className="flex justify-between items-center pt-2">
              <span className="text-gray-600 text-sm">1/6 DUE DATE</span>
              <span className="text-gray-900 font-medium">
                {loanDetails.dueDate}
              </span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-gray-600 text-sm">DUE AMOUNT</span>
              <span className="text-gray-900 font-medium">
                N{loanDetails.dueAmount.toLocaleString()}.00
              </span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-gray-600 text-sm">MONTHLY REPAYMENT</span>
              <span className="text-gray-900 font-medium">
                N{loanDetails.monthlyRepayment.toLocaleString()}.00
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}